Effectively use async/await with ASP.NET Web API

前端 未结 4 1960
生来不讨喜
生来不讨喜 2020-11-30 16:40

I am trying to make use of the async/await feature of ASP.NET in my Web API project. I am not very sure whether it will make any difference in performance of my

4条回答
  •  粉色の甜心
    2020-11-30 17:25

    It is correct, but perhaps not useful.

    As there is nothing to wait on – no calls to blocking APIs which could operate asynchronously – then you are setting up structures to track asynchronous operation (which has overhead) but then not making use of that capability.

    For example, if the service layer was performing DB operations with Entity Framework which supports asynchronous calls:

    public Task>> ReturnAllCountries()
    {
        using (db = myDBContext.Get()) {
          var list = await db.Countries.Where(condition).ToListAsync();
    
           return list;
        }
    }
    

    You would allow the worker thread to do something else while the db was queried (and thus able to process another request).

    Await tends to be something that needs to go all the way down: it is very hard to retro-fit into an existing system.

提交回复
热议问题