2

我最近发现了 CTP 异步库,我想尝试编写一个玩具程序来熟悉新概念,但是我遇到了一个问题。

我相信代码应该写出来

Starting
stuff in the middle
task string

但事实并非如此。这是我正在运行的代码:

namespace TestingAsync
{
    class Program
    {
        static void Main(string[] args)
        {
            AsyncTest a = new AsyncTest();
            a.MethodAsync();
        }
    }

    class AsyncTest
    {
        async public void MethodAsync()
        {
            Console.WriteLine("Starting");
            string test = await Slow();
            Console.WriteLine("stuff in the middle");
            Console.WriteLine(test);
        }

        private async Task<string> Slow()
        {
            await TaskEx.Delay(5000);
            return "task string";
        }
    }
}

有任何想法吗?如果有人知道一些很好的教程和/或演示这些概念的视频,那就太棒了。

4

2 回答 2

5

您正在调用异步方法,然后只是让您的应用程序完成。选项:

  • Thread.Sleep(或 Console.ReadLine)添加到您的Main方法中,这样您就可以在后台线程上发生异步内容时休眠
  • 让你的异步方法返回Task并等待你的Main方法。

例如:

using System;
using System.Threading.Tasks;

class Program
{
    static void Main(string[] args)
    {
        AsyncTest a = new AsyncTest();
        Task task = a.MethodAsync();
        Console.WriteLine("Waiting in Main thread");
        task.Wait();
    }
}

class AsyncTest
{
    public async Task MethodAsync()
    {
        Console.WriteLine("Starting");
        string test = await Slow();
        Console.WriteLine("stuff in the middle");
        Console.WriteLine(test);
    }

    private async Task<string> Slow()
    {
        await TaskEx.Delay(5000);
        return "task string";
    }
}

输出:

Starting
Waiting in Main thread
stuff in the middle
task string

在视频方面,我在今年早些时候在 Progressive .NET 上做了一个关于异步的会议——视频是在线的。此外,我还有许多关于 async 的博客文章,包括我的Eduasync系列。

此外,还有很多来自 Microsoft 团队的视频和博客文章。有关大量资源,请参阅Async 主页

于 2011-12-08T05:11:52.053 回答
1

您在 5000 毫秒之前退出程序。

于 2011-12-08T05:12:56.163 回答