Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
89 views
in Technique[技术] by (71.8m points)

c# - How to await on async delegate

In one of MVA videos i saw next construction:

static void Main(string[] args)
{
    Action testAction = async () =>
    {
        Console.WriteLine("In");
        await Task.Delay(100);
        Console.WriteLine("After first delay");
        await Task.Delay(100);
        Console.WriteLine("After second delay");
    };

    testAction.Invoke();
}

Result of execution will be:

In
Press any key to continue . . .

It's perfectly compiles, but right now i don't see any way to await it. I might put Thread.Sleep or Console.ReadKey after invocation, but that's not what i want.

So how this delegate should be modified to become awaitable?(or at least how can i track that execution completed?)

Is there are any practical usage of such delegates?

question from:https://stackoverflow.com/questions/23285753/how-to-await-on-async-delegate

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In order for something to be awaited, it has to be awaitable. As void is not so, you cannot await on any Action delegate.

An awaitable is any type that implements a GetAwaiter method, which returns a type that implements either INotifyCompletion or ICriticalNotifyCompletion, like Task and Task<T>, for example.

If you want to wait on a delegate, use Func<Task>, which is an equivalent to a named method with the following signature:

public Task Func()

So, in order to await, change your method to:

static void Main(string[] args)
{
    Func<Task> testFunc = async () =>
    {
        Console.WriteLine("In");
        await Task.Delay(100);
        Console.WriteLine("First delay");
        await Task.Delay(100);
        Console.WriteLine("Second delay");
    };
}

And now you can await it:

await testFunc();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...