【问题标题】:async methods and internal looping异步方法和内部循环
【发布时间】:2016-09-07 18:19:14
【问题描述】:

我有一个与内部 Web API 交互的控制台应用程序。它有时运行正确,但有时它会无缘无故地抛出异常,我找不到。我唯一的怀疑是,可能是因为我使用的每个方法都不是异步的。

从这里开始:

我的控制台应用程序运行异步方法 Process():

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

Process() 连接到内部网络应用程序:

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);
    }

}

这是内部网络 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() 的循环中收集的数据使用的方法不是任务或异步的。

我是否需要确保异步方法中使用的每个方法也是异步的?

谢谢!

【问题讨论】:

    标签: .net c#-4.0 async-await


    【解决方案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;
    }
    

    不过,这并不能解决您的异常问题。

    我唯一的怀疑是,这可能是因为我使用的每个方法都不是异步的。

    不,这不会导致异常。

    【讨论】:

    • 谢谢。我相信我需要使一切异步,因为 MyStuff.GetStuff() 调用外部 webAPI。因此,控制台应用程序需要等待所有这些 WebAPI 内容完成,然后才能向用户输出数据。
    猜你喜欢
    • 2018-10-17
    • 2017-10-22
    • 1970-01-01
    • 1970-01-01
    • 2017-08-21
    • 1970-01-01
    • 2018-07-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多