到Task.Run或不Task.Run [英] To Task.Run or not to Task.Run

查看:247
本文介绍了到Task.Run或不Task.Run的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有,其中包括异步方法的接口,并且我有两个不同的接口的实现。一两个实现的自然是异步,并且另一种是不。什么是执行非异步方法最正确的方法是什么?

Suppose I have an interface which includes an async method, and I have two different implementations of that interface. One of the two implementations is naturally async, and the other is not. What would be the "most correct" way of implementing the non-async method?

public interface ISomething {
    Task<Foo> DoSomethingAsync();
}

// Normal async implementation
public class Implementation1 : ISomething {
    async Task<Foo> ISomething.DoSomethingAsync() {
        return await DoSomethingElseAsync();
    }
}

// Non-async implementation
public class Implementation2 : ISomething {
    // Should it be:
    async Task<Foo> ISomething.DoSomethingAsync() {
        return await Task.Run(() => DoSomethingElse());
    }
    // Or:
    async Task<Foo> ISomething.DoSomethingAsync() {
        return DoSomethingElse();
    }
}

我尽量保持与斯蒂芬·克利里的博客,我知道这些没有一个真正提供任何异步的好处,我很确定这一点。第二个似乎更正确的对我来说,因为它没有pretend要的东西它不是,但它确实给一个编译器警告,这些加起来,让分散注意力。

I try to keep up with Stephen Cleary's blog, and I know neither one of these actually provides any async benefits, and I'm ok with that. The second one seems more correct to me, since it doesn't pretend to be something it's not, but it does give a compiler warning, and those add up and get distracting.

这都将是内部的ASP.NET(包括网络MVC和的WebAPI),如果有差别。

This would all be inside ASP.NET (both web MVC and WebAPI), if that makes a difference.

推荐答案

您可以完全放弃异步修改器,并使用 Task.FromResult 来同步返回一个完成的任务:

You can forgo the async modifier altogether and use Task.FromResult to return a completed task synchronously:

Task<Foo> ISomething.DoSomethingAsync()
{
    return Task.FromResult(DoSomethingElse());
}

这需要警告的关怀,具有更好的性能,因为它并不需要的的状态机的开销异步方法。

This takes care of the warning and has better performance as it doesn't need the state machine overhead of an async method.

但是,这并改变异常处理的比特的语义。如果这是一个问题,那么你应该使用同步异步法的做法并接受警告(或将其关闭了评论):

However, this does change the semantics of exception handling a bit. If that's an issue then you should use the synchronous async method approach and accept the warning (or turn it off with a comment):

#pragma warning disable 1998
    async Task<Foo> ISomething.DoSomethingAsync() 
#pragma warning restore 1998
    {
        return DoSomethingElse();
    }

由于斯蒂芬·克利建议你也可以采取警告护理(同时保持同步的方法),通过在等待一个已经完成的任务:

As Stephen Cleary suggested you can also take care of that warning (while keeping the method synchronous) by awaiting an already completed task:

async Task<Foo> ISomething.DoSomethingAsync() 
{
    await Task.FromResult(false); // or Task.CompletedTask in .Net 4.6
    return DoSomethingElse();
}

这篇关于到Task.Run或不Task.Run的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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