【问题标题】:C# await task Console splash [duplicate]C#等待任务控制台启动[重复]
【发布时间】:2017-07-28 02:26:39
【问题描述】:
static void Main(string[] args)
{ print(); }

static async void print()
{
    try
    {
        await Task.Factory.StartNew(() =>
        {
            Thread.Sleep(3000);
            Console.WriteLine("3");
            Debug.Write("3");
        });
    }
    catch (Exception)
    { }
    Console.Read();
}

控制台飞溅没有任何错误发生!

【问题讨论】:

    标签: .net task console-application


    【解决方案1】:

    发生这种情况是因为print 方法被并行调用,所以main 继续,因为没有其他事情可做,所以它返回。 main 完成后程序退出。

    如果您希望它等待print 方法,请将其更改为返回Task 而不是void,然后在Main 方法中等待该任务:

    static void Main(string[] args)
    { print().Wait(); }
    
    static async Task print() {...}
    

    【讨论】:

      猜你喜欢
      • 2010-12-21
      • 1970-01-01
      • 2021-09-27
      • 1970-01-01
      • 2023-03-23
      • 2020-12-12
      • 1970-01-01
      • 2020-02-11
      • 1970-01-01
      相关资源
      最近更新 更多