C# 异步编程问题

C# 异步编程问题,c#,asynchronous,async-ctp,C#,Asynchronous,Async Ctp,我最近发现了CTP异步库,我想尝试编写一个玩具程序来熟悉新概念,但是我遇到了一个问题 我相信代码应该写出来 Starting stuff in the middle task string 但事实并非如此。下面是我运行的代码: namespace TestingAsync { class Program { static void Main(string[] args) { AsyncTest a = new AsyncT

我最近发现了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";
        }
    }
}
命名空间测试同步
{
班级计划
{
静态void Main(字符串[]参数)
{
AsyncTest a=新的AsyncTest();
a、 MethodAsync();
}
}
类异步测试
{
异步公共void方法异步()
{
控制台写入线(“启动”);
字符串测试=等待慢();
Console.WriteLine(“中间的东西”);
控制台写入线(测试);
}
专用异步任务Slow()
{
等待TaskEx.延迟(5000);
返回“任务字符串”;
}
}
}

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

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

  • 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";
    }
}
在视频方面,我在今年早些时候在Progressive.NET上做了一次关于异步的会议。此外,我还有很多,包括我的系列


此外,微软团队还发布了大量视频和博客文章。有关大量资源,请参阅。

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

您的第二个选项就是我要寻找的。在完成
MethodAsync()
return
Task
之后,我能够调用
a.MethodAsync().wait()
Main
,它成功了!
Starting
Waiting in Main thread
stuff in the middle
task string