简体   繁体   中英

Is there a way to start a task only when “await” happens?

Considering:

"Only methods that return void, Task, or Task can be marked as async..."

If I need to invoke a logic or starting something only when the task is "awaited", in this case when the method OnCompleted(Action continuation) or UnsafeOnCompleted(Action continuation) of TaskAwaiter implementation, somehow can I do it?

For example:

I need to mock some implementation that returns Task<T> , is this case my mock required to use and to continue in just one Thread , but in no way to manipulate the SynchronizationContext .

I know it's a very specific scenario, but is just for theory. Likewise there's the Unwrap() method, is there something like Wrap(IAwaitable accessAwaiter) ?

If the Task only starts when the await is "awaited", it already solves my problem. Thanks for any help.

不可以。但是,如果您确实需要这样做,可以编写自己的模拟服务员。

I do not advise doing this, but yes you can start a Task when an await happens.

Here is a toy example that, again, I do not advise using:

public static TaskAwaiter GetAwaiter(this TimeSpan timeSpan) 
{ 
    return Task.Delay(timeSpan).GetAwaiter();
}

Usage:

await TimeSpan.FromSeconds(3);

Similar to how a foreach loop expands to code that calls GetEnumerator() on the enumerable, await <expression> is an expression that expands to something that calls (<expression>).GetAwaiter() with a bunch of other magic to make continuations happen.

Edit

If all you want is to await a Task that may not yet be started, starting it if it has not yet started, you can simply use this:

public static Task EnsureStarted(this Task task)
{
    if (task.Status == TaskStatus.Created)
    {
        try
        {
            task.Start();
        }
        catch (InvalidOperationException) { }
    }
    return task;
}

And use like so:

await task.EnsureStarted();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM