更改服务器端WebAPI以获得异步/等待的好处 [英] Changing my server-side WebAPI to get the benefits of async/await

查看:58
本文介绍了更改服务器端WebAPI以获得异步/等待的好处的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图了解服务器端异步/等待使用.我的理解是,只有在可以释放线程时,它才有用. 如果我有:

Trying to understand server-side async/await use. My understanding is that it is only useful when the thread can be freed. If I have:

[HttpGet]
public async Task<IEnumerable<MyObject>> Get()
{        
     return await Task<IEnumerable<MyObject>>.Run(() => DoThingsAndGetResults());
}

IEnumerable<MyObject> DoThingsAndGetResults()
{
    // ...Do some CPU computations here...

    IEnumerable<MyObject> result = myDb.table.Select().ToList(); // entity framework

    // ...Do some CPU computations here...

    return result;
}

该线程将被释放吗?在这种情况下,Async/Await是没有用的吗?从异步/等待中获利的唯一方法是,如果我进行一些较大的更改并执行以下操作:

Will the thread ever be freed? Is Async/Await useless in this case? Is the only way to gain benefit from async/await is if I make some bigger changes and do this:

[HttpGet]
public async Task<IEnumerable<MyObject>> Get()
{        
     return await DoThingsAndGetResultsAsync();
}

async IEnumerable<MyObject> DoThingsAndGetResultsAsync()
{
    // ...Do some CPU computations here...

    IEnumerable<MyObject> result = await myDb.table.Select().ToListAsync(); // entity framework

    // ...Do some CPU computations here...

    return result;
}

推荐答案

如果要实现的目的是释放线程,则第二个示例更好.第一个在整个操作过程中都拥有一个线程.

If what you want to achieve is to free threads, the second example is better. The first one holds a thread throughout the operation.

async-await的全部作用只是简单地帮助您编写异步运行但看起来"完整的代码.同步.

All that async-await does is to simply helps you write code that runs asynchronously but "looks" synchronous.

异步代码有两个原因:

  1. 卸载.主要用于GUI线程,或其他更重要"的线程.线程". (在等待CPU操作完成时释放线程.)
  2. 可扩展性.主要用于服务器端以减少资源使用. (在等待IO完成时释放线程.)
  1. Offloading. Used mostly in GUI threads, or other "more important" threads". (Releasing threads while waiting for CPU operations to complete).
  2. Scalability. Used mainly in the server-side to reduce resource usage. (Releasing threads while waiting for IO to complete).

毫不奇怪,原因与您的示例相符.

Unsurprisingly the reasons match your examples.

在第一个示例中,您在另一个线程(使用Task.Run)上运行DoThingsAndGetResults并等待其异步完成.第一个线程正在释放,而第二个线程没有释放.

In the first example you run DoThingsAndGetResults on a different thread (using Task.Run) and waiting for it to complete asynchronously.The first thread is being released, but the second one doesn't.

在第二个中,您一次只使用1个线程,并且在等待IO(实体框架)时将其释放.

In the second one you only use 1 thread at a time, and you release it while waiting for IO (Entity Framework).

这篇关于更改服务器端WebAPI以获得异步/等待的好处的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆