Most suitable way to return hot, awaited task from F # to the caller in C # framework
It seems like the following situation often occurs and I am wondering,
- What would be the most appropriate and shortest F # equivalent (for example, no additional tasks created, has the same
SynchronizationContext
, etc.)? - Is there anything that needs to be fixed or improved:
Here DoAsync
is a member function derived from the framework class, it takes a parameter and returns a hot awaited task to the caller, which is some framework function.
In C #:
public async Task DoAsync(int x)
{
if(x == 10)
{
await taskContext.ReturnAsync();
}
}
Here Async.Ignore
is from here
In F #:
member x.DoAsync(int x) =
async {
if x = 10
return! Async.AwaitTask(taskContext.ReturnAsync() |> Async.Ignore)
else
return! Async.AwaitTask(Task.FromResult(0))
} |> Async.StartAsTask :> Task
Look at Thomas's answer in an easier way. As an added note, in F # 4.0 this appears to be an overload for non-generic Task
. See this Visual F # Tools PR for details .
source to share
Using Async.AwaitTask
and Async.StartAsTask
is the way to go. Although you don't really need to return anything from async
, if you just want to return non-generic Task
:
member x.DoAsync(x:int) =
let work = async {
if x = 10 then
do! taskContext.ReturnAsync() |> Async.Ignore }
Async.StartAsTask(work) :> Task
source to share