2016-05-16 37 views
0

最近我正在學習任務和certailly我感動異步等待,我試圖寫一個簡單的演示,請親切地幫助檢查我的編碼是否有任何問題?爲什麼「x = ???」和「GetDataFromDbAsync結束」不會打印在控制檯上?如果你能幫我解決問題,我會非常自信。非常感謝。等待之後的文本不能打印出異步無效的方法

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

namespace ConsoleApplication8 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 

      Test test = new Test(); 
      Console.WriteLine("main thread starts..."); 
      System.Threading.Thread.Sleep(1000); 
      test.GetDataFromDb(); 
      Console.WriteLine("Mainthread end"); 
      Console.ReadKey(); 

     } 
    } 

    class Test 
    { 
     public void GetDataFromDb() 
     { 
      Console.WriteLine("GetDataFromDb starts"); 
      Task.Run(() => GetDataFromDbAsync()); 
      Console.WriteLine("GetDataFromDb ends"); 
     } 

     public async Task<bool> GetDataFromDbAsync() 
     { 
      try 
      { 
       Console.WriteLine("GetDataFromDbAsync starts"); 
       var x = await ReadingDbAsync(); 
       Console.WriteLine("x=" + x); 
       Console.WriteLine("GetDataFromDbAsync ends"); 
       return true; 
      } 
      catch(AggregateException ex) 
      { 
       Console.WriteLine(ex.Message); 
       return false; 
      } 
     } 

     public Task<int> ReadingDbAsync() 
     { 
      Console.WriteLine("ReadingDbAsync starts"); 
      System.Threading.Thread.Sleep(3000); 
      var task= new Task<int>(() => 100); 
      Console.WriteLine("ReadingDbAsync ends"); 
      return task; 
     } 
    } 
} 

以下是輸出, demo output here

輸出如下:

main thread starts... 
GetDataFromDb starts 
GetDataFromDb end 
Mainthread end 
GetDataFromDbAsync starts 
ReadingDbAsync starts 
ReadingDbAsync ends 
**BUT WHY NOT SHOW THE FOLLOWING 
x=100 
GetDataFromDbAsync ends** 

回答

1

你的問題是,你正在使用的任務建構:

var task= new Task<int>(() => 100); 

如果您想要表示同步值的任務,請使用Task.FromResult

var task = Task.FromResult(100); 

正如我在我的博客上描述的那樣,you should never, ever use task constructors

+0

非常感謝您的回答,這是可行的。 – Jacob

1

你不是await荷蘭國際集團正在創建中GetDataFromDb任務。因此,在狀態機在GetDataFromDbAsync中的await之後恢復之前,執行將執行Console.ReadKey。我懷疑,如果你按了一個鍵,在應用程序退出之前你會看到你的兩個控制檯消息丟失。

你需要返回一個TaskGetDataFromDb,並確保它已完成:

test.GetDataFromDb().Wait(); 

而且,看到this related question