2016-09-06 120 views
0

我有一個與內部Web API交互的控制檯應用程序。它有時會正確運行,但有時它會拋出異常,我無法找到任何理由。我唯一的懷疑是,也許是因爲我使用的每種方法都不是異步的。異步方法和內部循環

這裏是它開始:

我的控制檯應用程序運行異步方法的工序():

static void Main(string[] args) 
    { 
    Process().Wait(); 
} 

流程()連接到一個內腹板APPI:

private static async Task Process() 
    { 

    using (var http = new HttpClient()) 
     { 
      http.BaseAddress = new Uri("http://localhost:112345/"); 
      var response = await http.PostAsJsonAsync("/api/PostStuff", data); 
      var result = response.Content.ReadAsStringAsync().Result; 
      Console.WriteLine(result); 
    } 

} 

這裏是內部Web API:

[HttpPost("api/PostStuff")] 
    public async Task<string> PostStuff([FromBody] Data data) 
    { 
     foreach (var s in MyStuff.GetStuff() 
     { 
      // for loop that gets data from another class that is not asynchronous 
     } 
     return stuff; 
    } 

我擔心的是,從使用MyStuff.GetStuff()的循環中收集的數據使用非任務或異步方法。

我是否需要確保異步方法中使用的每種方法都是異步的?

謝謝!

回答

1

我是否需要確保異步方法中使用的每種方法都是異步?

沒有,但沒有點有你的WebAPI方法是async如果它不具有任何異步工作要做:

[HttpPost("api/PostStuff")] 
public string PostStuff([FromBody] Data data) 
{ 
    foreach (var s in MyStuff.GetStuff() 
    { 
    // for loop that gets data from another class that is not asynchronous 
    } 
    return stuff; 
} 

這不會解決你的異常問題,雖然。

我唯一的懷疑是,也許這是因爲我使用的每種方法都不是異步的。

不,這不會導致異常。

+0

謝謝。我相信我需要做一切異步,因爲MyStuff.GetStuff()調用外部webAPI。因此,控制檯應用程序需要等待所有這些WebAPI內容完成才能向用戶提供數據。 – SkyeBoniwell