2011-12-08 109 views
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"; 
     } 
    } 
} 

任何想法?如果有人知道展示這些概念的一些很好的教程和/或視頻,那將會非常棒。

回答

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 

在視頻方面,我做了異步會話在今年早些時候在進步.NET - the video is online。此外,我有一些blog posts about async,包括我的Eduasync系列。

此外,還有很多來自Microsoft團隊的視頻和博客文章。請參閱Async Home Page瞭解大量資源。

+0

你的第二個選擇是我正在尋找的。在使'MethodAsync()'返回Task後,我可以從'Main'調用'a.MethodAsync()。wait();',它工作正常! – JesseBuesking

1

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