简体   繁体   English

异步执行代码

[英]Code execution with async

Sometimes when I run code made asynchronous using async and await , I find that some parts of the code don't even get executed. 有时,当我运行使用asyncawait进行异步处理的代码时,我发现代码的某些部分甚至无法执行。 For example in the following code, "Sleeping2" is not shown on the console screen: 例如,在以下代码中,控制台屏幕上未显示“ Sleeping2”:

public static void Sleeping(int millis)
{
    System.Console.WriteLine("Sleeping1");
    System.Threading.Thread.Sleep(millis);
    System.Console.WriteLine("Sleeping2");
}

public static async void SleepingAsync(int millis)
{
    await System.Threading.Tasks.Task.Run(() => Sleeping(millis));
}

public static async void DoSleepingMain()
{
    System.Console.WriteLine("DoSleepingMain1");
    SleepingAsync(12000);
    System.Console.WriteLine("DoSleepingMain2");
}

public static void Main(string[] args)
{
    DoSleepingMain();
}

Another example is the following in which neither Sleeping1 or Sleeping2 are displayed. 下面是另一个示例,其中不显示Sleeping1或Sleeping2。 I don't understand this because I await the Task in the DoSleepingMain method. 我不明白这一点,因为我正在await DoSleepingMain方法中的Task。

public static void Sleeping(int millis)
{
    System.Console.WriteLine("Sleeping1");
    System.Threading.Thread.Sleep(millis);
    System.Console.WriteLine("Sleeping2");
}

public static async Task SleepingAsync(int millis)
{
    System.Threading.Tasks.Task.Run(() => Sleeping(millis)); //warning: call not awaited
}

public static async void DoSleepingMain()
{
    System.Console.WriteLine("DoSleepingMain1");
    await SleepingAsync(12000);
    System.Console.WriteLine("DoSleepingMain2");
}

public static void Main(string[] args)
{
    DoSleepingMain();
}

Any explanation (or pointer to explanations) would be appreciated! 任何解释(或指向解释的指针)将不胜感激! Thanks 谢谢

You've just discovered why you should never write async void . 您刚刚发现了为什么不应该编写async void

If you write an async void method, you have no way of knowing when the asynchronous part finishes. 如果编写async void方法,则无法知道异步部分何时完成。

This includes Main() ; 这包括Main() ; your program is exiting as soon as it hits the first await . 您的程序在第一次await就退出。

async methods are mostly useless in console programs; async方法在控制台程序中几乎没有用; if you really want to try them, you'll need to call .Wait() on the Task s returned to Main() . 如果您真的想尝试使用它们,则需要在返回给Main()Task上调用.Wait() Main()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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