How to await on async delegate

前端 未结 3 1331
伪装坚强ぢ
伪装坚强ぢ 2021-02-01 02:17

In one of MVA videos i saw next construction:

static void Main(string[] args)
{
    Action testAction = async () =>
    {
        Console.WriteLine(\"In\");
          


        
相关标签:
3条回答
  • 2021-02-01 02:47

    Recently I found that NUnit able to await async voidtests. Here is good description how it works: How does nunit successfully wait for async void methods to complete?

    You won't use it in regular tasks, but it's good to know that it is possible

    0 讨论(0)
  • 2021-02-01 02:52

    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();
    
    0 讨论(0)
  • 2021-02-01 03:00

    "Async void is for top-level event-handlers only",

    http://channel9.msdn.com/Series/Three-Essential-Tips-for-Async/Tip-1-Async-void-is-for-top-level-event-handlers-only

    0 讨论(0)
提交回复
热议问题