简体   繁体   English

异步方法调用非异步方法最佳实践

[英]Async Method Call Non-Async Method Best Practices

For some reason I need to inherit a class to implement an Async method which is the below implementation that it is best practices出于某种原因,我需要继承一个 class 来实现一个异步方法,这是下面的实现,它是最佳实践

1. 1.

protected override Task<TResult> OnExecuteAsync<TResult><TResult>()
{
        return Task.Run<TResult>(() => DoSomething());
}
protected override async Task<TResult> OnExecuteAsync<TResult><TResult>()
{
        return await Task.Run<TResult>(() => DoSomething());
}

I want to know which one is the best implementation?我想知道哪一个是最好的实现?

Thank you谢谢

In short, if the base class or interface is expecting a Task result and you have synchronous method and it doesn't need to run in a task, all you need to do is give it a pre-completed task .简而言之,如果基础class接口期待Task结果,并且您有同步方法并且不需要在任务中运行,您只需给它一个预先完成的任务

The simplest thing to do, would be just leave the async keyword , return the result, and ignore (or pragma out) the warning.最简单的做法就是留下async关键字,返回结果,然后忽略(或pragma out)警告。 You do not need to spin-up a new task via Task.Run (this would be an inefficient way of achieving nothing).不需要通过Task.Run启动任务(这将是一种无所作为的低效方式)。 In this case the compiler automatically takes care of everything for you (albeit with a warning that you have nothing to await)在这种情况下,编译器会自动为您处理所有事情(尽管警告您没有什么可等待的)

protected override async Task<TResult> OnExecuteAsync<TResult>()
{
    return DoSomething();
}

You could also use Task.FromResult to create the pre-completed task .您还可以使用Task.FromResult创建预先完成的任务 The only caveat is if the consumer is calling await , in which case you should be nice and make sure any exceptions are returned on the resulting Task with Task.FromException .唯一需要注意的是,如果消费者正在调用await ,在这种情况下,您应该很好,并确保使用Task.FromException在生成的Task上返回任何异常 This is analogous to what the compiler generated IAsyncStateMachine implementation ( async and await pattern ) would automatically do.这类似于编译器生成IAsyncStateMachine实现( async 和 await 模式)会自动执行的操作。

protected override Task<TResult> OnExecuteAsync<TResult>()
{
    try
    {
        return Task.FromResult(DoSomething());
    }
    catch(exception ex)
    { 
        // place any exception on the returned task
        return Task.FromException<TResult>(ex);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM