当前位置:网站首页>C # use awaiter

C # use awaiter

2022-07-05 03:39:00 Dotnet cross platform

2a2892df6d2960d4621199a30304e48c.png Can be provided to any GetAwaiter Method and return awaiter Object using async keyword .awaiter use OnCompleted Method realization INotifyCompletion Interface . This method is called when the task is completed . The following code snippet is not used in a task await, But using tasks GetAwaiter Method .Task Class GetAwaiter Return to one TaskAwaiter. Use OnCompleted Method , Assign a local function to be called when the task is complete :

private static void CallerWithAwaiter()
{
  TraceThreadAndTask($"starting {nameof(CallerWithAwaiter)}");
  TaskAwaiter<string> awaiter = GreetingAsync("Matthias").GetAwaiter();
  awaiter.OnCompleted(OnCompleteAwaiter);
  void OnCompleteAwaiter()
  {
    Console.WriteLine(awaiter.GetResult());
    TraceThreadAndTask($"ended {nameof(CallerWithAwaiter)}");
  }
}

When running the application , The result is similar to that you use wait Keyword case :

starting CallerWithAwaiter in thread 2 and no task 
running GreetingAsync in thread 3 and task 1 
running Greeting in thread 3 and task 1 
Hello,Matthias
ended CallerWithAwaiter in thread 3 and no task

The compiler the await Put all the code after the keyword into OnCompleted Method to convert await keyword .

原网站

版权声明
本文为[Dotnet cross platform]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140728263967.html