2016-09-06 111 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