2014-09-01 89 views
3

你好,我想了解任務和異步方法的概念。我一直在玩這段代碼有一段時間沒有用。有人能告訴我如何從test()方法得到返回值並將該值賦給變量?如何獲得異步方法的返回值?

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace ConsoleApplication2 
{ 
    class Program 
    { 

    static void Main(string[] args) 
    { 

     Task test1 = Task.Factory.StartNew(() => test()); 
     System.Console.WriteLine(test1); 
     Console.ReadLine(); 
    } 

    public static async Task<int> test() 
    { 
     Task t = Task.Factory.StartNew(() => { Console.WriteLine("do stuff"); }); 
     await t; 
     return 10; 
    } 
} 
} 
+0

看看我的[curah](http://curah.microsoft.com/45553/asyncawait-general「async-await General」)上的文章。 – 2014-09-01 10:43:02

回答

2

來獲取值了Task可以await其異步等待完成任務的任務,然後返回結果。另一個選項是呼叫Task.Result,它阻止當前線程,直到結果可用。這會導致GUI應用程序中的deadlock,但在控制檯應用程序中可以使用,因爲它們沒有SynchronizationContext

你不能在Main方法使用await,因爲它不能async這麼一個選擇是使用test1.Result

static void Main(string[] args) 
{ 

    Task<int> test1 = Task.Factory.StartNew<int>(() => test()); 
    System.Console.WriteLine(test1.Result); // block and wait for the result 
    Console.ReadLine(); 
} 

另一種選擇是創建一個async方法,你從Main調用和await裏面的任務。您仍可能需要阻止等待async方法完成,因此您可以在該方法的結果上調用Wait()

static void Main(string[] args) 
{ 
    MainAsync().Wait(); // wait for method to complete 
    Console.ReadLine(); 
} 

static async Task MainAsync() 
{ 
    Task<int> test1 = Task.Factory.StartNew<int>(() => test()); 
    System.Console.WriteLine(await test1); 
    Console.ReadLine(); 
} 
+0

對於運行'test()'的任務,將'Task.Factory.StartNew'更改爲'Task.Factory.StartNew '。我更新瞭解決方案。 – 2014-09-01 06:05:13

+0

錯誤是因爲'Task'沒有'Result'屬性,而是'Task '。 – 2014-09-01 06:05:42

+3

當處理'async-await'時,使用'Task.Run'而不是'Task.Factory.StartNew'。 – 2014-09-01 10:40:25