I think you are looking for TaskCompletionSource
. This gives you the most flexibility. You can set exceptions on the task, mark it incomplete etc. Alternatively Task.FromResult
.
In many scenarios, it is useful to enable a Task to represent
an external asynchronous operation. TaskCompletionSource is
provided for this purpose. It enables the creation of a task that can
be handed out to consumers. The consumers can use the members of the
task the same way as they would in any other scenario handling task
member variables.
Consider the following options for both, I include the first, but you can't return a Task.CompletedTask<T>
, but if you just want to return a completed Task, eg cause maybe you had some out
parameters that have been set, then that might be your answer.
static async Task SomeMethod()
{
await Task.CompletedTask;
}
or - because we can't use await without async
static Task<bool> SomeOtherMethod()
{
var taskSource = new TaskCompletionSource<bool>();
taskSource.SetResult(true);
return taskSource.Task;
}
or (.Net 4.5+)
static Task<bool> SomeEvenOtherMethod()
{
return Task.FromResult(true);
}
or the async variant of the above
static async Task<bool> SomeEvenOtherMethod()
{
var taskSource = new TaskCompletionSource<bool>();
taskSource.SetResult(true);
return (await taskSource.Task);
}
Alternatively: (.Net 4.5+)
static async Task<bool> SomeEvenOtherMethod()
{
return(await Task.FromResult(true));
}
And with an IAsyncEnumerable
static async IAsyncEnumerable<bool> GetBoolsAsync()
{
var t = await SomeOtherMethod();
yield return t;
}
Or (.Net 4.5+)
static async IAsyncEnumerable<bool> GetBoolsAsync()
{
yield return await Task.FromResult(true);
}