在方法签名中使用异步关键字返回网站阿比端点任务关键字、阿比、任务、方法

2023-09-02 10:33:36 作者:夏天很爱西瓜

如果我想通过返回工作对象写一个无阻塞的网络API的行动,我可以使用或不使用异步做关键字这样:

If I wanted to write a non-blocking web api action by returning a Task object, I could do it with or without using the async keyword as such:

public async Task<HttpResponseMessage> Get()
{
    Func<HttpResponseMessage> slowCall = () =>
    {
        Thread.Sleep(2000);
        return Request.CreateResponse(HttpStatusCode.OK, "Hello world");
    };

    var task = Task<HttpResponseMessage>.Factory.StartNew(slowCall);
    return await task;
}

如果不使用异步

public Task<HttpResponseMessage> Get()
{
    Func<HttpResponseMessage> slowCall = () =>
    {
        Thread.Sleep(2000);
        return Request.CreateResponse(HttpStatusCode.OK, "Hello world");
    };

    var task = Task<HttpResponseMessage>.Factory.StartNew(slowCall);
    return task;
}

他们都正常工作。但是,每次我看到(在网上和书籍)上编写一个Web API的行动,返回工作使用异步关键字。当然,据我所知,您可以更灵活,因为它允许你控制你要等待的,什么不是。但是,假设你的功能可以有效的处理无论哪种方式,

They both work properly. However, every example I've seen (online and in books) on writing a web api action that returns a Task uses the async keyword. Granted, I understand that gives you more flexibility as it allows you to control what you want to "await" on and what not. But assuming your functionality could be effectively handled either way,

有没有任何优势,使用一种方法相较于其他? 我应该一直使用异步关键字(如果是,为什么)? 或者是无关紧要的?

推荐答案

异步关键字可以使用计谋在你的方法,通过创建一个状态机。如果你们能在不使用它,你可以继续删除它返回一个异步任务,因为它有一些(非常小的)的开销。但请记住,它是只在少数情况下是有用的。你的返回待机就是其中之一。

The async keyword allows you to use an await in your method by creating a state machine. If you can manage returning an asynchronous task without using it you can go ahead and remove it because it has some (very small) overhead. Keep in mind though that it's only useful in a few cases. Your return await is one of them.

另一个差别是如何处理异常。如果有,在方法的同步部分的例外,它被标记为异步的异常将被存储在返回的任务。如果没有关键字除了会定期抛出。例如,在这种情况下,有一个很大的不同:

Another difference is how exceptions are handled. If there's an exception in the synchronous part of the method and it's marked as async the exception will be stored in the returned task. Without the keyword the exception would be thrown regularly. For example in this case there's a big difference:

var task = Get(); // unhandled exception without async
try
{
    var result = await task; // handled exception with async
}
catch
{
}

我的建议是,即使使用异步关键字时,你不绝对需要*,因为大多数开发人员并不了解在优化的差异和价值主要是可以忽略不计。

My recommendation is to use the async keyword even when you don't absolutely need to*, because most developers don't understand the difference and the value in the optimization is mostly negligible.

*除非你和你的队友的真正的知道自己在做什么。

* Unless you and your teammates really know what you're doing.