异步编程问题

Jes*_*ing 2 c# asynchronous async-ctp

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

我相信代码应该写出来

Starting
stuff in the middle
task string
Run Code Online (Sandbox Code Playgroud)

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

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";
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?如果有人知道一些很好的教程和/或视频来展示这些概念,那将会很棒.

Jon*_*eet 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";
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

Starting
Waiting in Main thread
stuff in the middle
task string
Run Code Online (Sandbox Code Playgroud)

在视频方面,我在今年早些时候在Progressive .NET上进行了异步会话 - 视频在线.另外,我有很多关于异步博客文章,包括我的Eduasync系列.

此外,微软团队还有很多视频和博客文章.有关大量资源,请参阅Async主页.