3

我正在尝试学习 .NET 4.5 的异步和等待功能。首先这是我的代码

    static async void Method()
    {
        await Task.Run(new Action(DoSomeProcess));
        Console.WriteLine("All Methods have been executed");
    }

    static void DoSomeProcess()
    {
        System.Threading.Thread.Sleep(3000);
    }

    static void Main(string[] args)
    {
        Method();
        //Console.WriteLine("Method Started");
        Console.ReadKey();
    }

这段代码在控制台上没有给我任何结果。我不明白为什么。我的意思是不是任务假设只是没有阻塞的线程。但是,如果我在 main 方法中取消注释 Console.WriteLine() 一切似乎工作正常。

谁能告诉我这里发生了什么?

4

2 回答 2

11

对于 async/await 模式,有些事情与以前的线程不同。

  1. 你不应该使用System.Threading.Thread.Sleep ,因为这仍然是阻塞的并且不适用于异步。而是使用Task.Delay

  2. 考虑让所有代码异步。只有控制台中的 Main 方法不能与原因异步

  3. 避免async void方法。基本上 async void 仅适用于无法返回某些内容的事件处理程序。所有其他异步方法应返回TaskTask<T>

修改了您的示例:

    static async Task Method()
    {
        await DoSomeProcess();
        Console.WriteLine("All Methods have been executed");
    }

    static async Task DoSomeProcess()
    {
        await Task.Delay(3000);
    }

现在更改您的 Main 方法,因为这应该是您开始任务的地方

    Task.Run(() => Method()).Wait();
    //Console.WriteLine("Method Started");
    Console.ReadKey();
于 2013-10-12T15:01:27.680 回答
2

学习如何正确使用asyncawait关键字有一个小的学习曲线。

问题是没有人在等待谁在等待,还有一些其他细节,例如SyncronizationContextand Task

你应该查看一些文章:http: //msdn.microsoft.com/en-us/library/vstudio/hh191443.aspx

要在控制台中使用 async 和 await 关键字,您需要额外的代码: Can't specify the 'async' modifier on the 'Main' method of a console app or Await a Async Void method call for unit testing or Unit Test Explorer does not显示 Metro 应用程序的异步单元测试

我通常这样做:

static void Main(string[] args)
{
    Console.WriteLine("HELLO WORLD");
    var t1 = Task.Factory.StartNew(new Func<Task>(async () => await Method()))
        .Unwrap();
    Console.WriteLine("STARTED");
    t1.Wait();
    Console.WriteLine("COMPLETED");
    Console.ReadKey();
}

static async Task Method()
{
    // this method is perfectly safe to use async / await keywords
    Console.WriteLine("BEFORE DELAY");
    await Task.Delay(1000);
    Console.WriteLine("AFTER DELAY");
}
于 2013-10-12T15:05:13.300 回答