C# async tasks waiting indefinitely

后端 未结 2 923
醉梦人生
醉梦人生 2021-02-20 01:48

I am trying to use the functionality provided by \"async\" & \"await\" to asynchronously download webpage content and I have into issues where the Tasks are waiting forever

2条回答
  •  旧巷少年郎
    2021-02-20 02:17

    First, make sure you're running on .NET 4.5, not .NET 4.0. ASP.NET was made async-aware in .NET 4.5.

    Then, the proper solution is to await the result of Task.WhenAll:

    var tasks = websites.Select(GenerateSomeContent);
    await Task.WhenAll(tasks);
    

    The ASP.NET pipeline (in .NET 4.5 only) will detect that your code is awaiting and will stall that request until Page_Load runs to completion.

    Synchronously blocking on a task using Wait in this situation causes a deadlock as I explain on my blog.

提交回复
热议问题