Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Async.AwaitTask on plain Task (not Task<T>)?

Tags:

async-await

f#

I'm trying to consume a C# library in F#. The library makes heavy use of async/await. I want to use within an async { ... } workflow in F#.

I see we can Async.AwaitTask on async C# methods returning Task<T>, but what about those returning plain Task?

Perhaps, is there a helper to convert these to Async<unit> or to convert Task to Task<unit> so it will work with Async.AwaitTask?

like image 917
AshleyF Avatar asked Nov 05 '11 20:11

AshleyF


People also ask

Can we use async without task?

Run is basically asynchronous I/O to the CPU worker thread it just created - but the actual work you're doing is still CPU work, not asynchronous I/O. Implementing a method with the async keyword without using await raises a compiler warning. You could remove the async keyword and use "return Task.

What happens if we execute an asynchronous method but don't await it?

The call to the async method starts an asynchronous task. However, because no Await operator is applied, the program continues without waiting for the task to complete. In most cases, that behavior isn't expected.

How do I return a task without await?

C# Language Async-Await Returning a Task without awaitThere is only one asynchronous call inside the method. The asynchronous call is at the end of the method. Catching/handling exception that may happen within the Task is not necessary.

How do I create async task?

You can use await Task. Yield(); in an asynchronous method to force the method to complete asynchronously. Insert it at beginning of your method and it will then return immediately to the caller and complete the rest of the method on another thread.


1 Answers

You can use ContinueWith:

let awaitTask (t: Task) = t.ContinueWith (fun t -> ()) |> Async.AwaitTask 

Or AwaitIAsyncResult with infinite timeout:

let awaitTask (t: Task) = t |> Async.AwaitIAsyncResult |> Async.Ignore 
like image 70
zeuxcg Avatar answered Sep 21 '22 12:09

zeuxcg