【问题标题】:async Programming Issues异步编程问题
【发布时间】:2012-04-06 22:41:25
【问题描述】:

我最近发现了 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";
        }
    }
}

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

【问题讨论】:

    标签: c# asynchronous async-ctp


    【解决方案1】:

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

    • 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 -the video is online 上做了一个关于异步的会议。另外,我有很多blog posts about async,包括我的Eduasync 系列。

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

    【讨论】:

    • 您的第二个选项正是我想要的。在使MethodAsync() 返回Task 后,我可以从Main 调用a.MethodAsync().wait();,并且成功了!
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2018-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-09
      • 2020-11-22
      • 2017-04-01
      相关资源
      最近更新 更多