简体   繁体   English

什么都不做的异步方法

[英]Asynchronous method that does nothing

I have an interface IAnimation which exposes a method BeginAsync() .我有一个接口IAnimation公开了一个方法BeginAsync() That method should start the animation and return when it is completed.该方法应该启动动画并在完成后返回。

What I would like to do is implement a null animation class NoAnimation that just returns when it executes BeginAsync() .我想做的是实现一个null动画类NoAnimation ,它只在执行BeginAsync()时返回。

Is this the right implementation?这是正确的实施吗?

public async Task BeginAsync()
{
    await Task.Run(() => { });
}

I suspect that there is a more elegant approach than this.我怀疑有比这更优雅的方法。 I also considered creating an empty method.我还考虑过创建一个空方法。 But that gives me a warning which I don't like either.但这给了我一个我也不喜欢的警告。

Just use Task.CompletedTask to return a completed task:只需使用Task.CompletedTask即可返回已完成的任务:

public Task BeginAsync()
{
     return Task.CompletedTask;
}

If you have a Task<TResult> use Task.FromResult<TResult> to return a completed task with a result:如果你有一个Task<TResult>使用Task.FromResult<TResult>来返回一个已完成的任务和结果:

public Task<bool> BeginAsync()
{
     return Task.FromResult(true);
}

Your current implementation is very inefficient, as it builds the state machine, and also uses a ThreadPool thread to run the empty task.您当前的实现效率非常低,因为它构建了状态机,并且还使用 ThreadPool 线程来运行空任务。

I appreciate this doesn't exactly answer the original question (or at least not in a way that isn't already in another answer).我很欣赏这并不能完全回答原始问题(或者至少不是以另一种答案中没有的方式)。 What it does it provide additional context for @ReedCopsey's answer, for those (including me! and others, based on the comments on that answer) who initially might find it hard to understand what is going on here.它为@ReedCopsey 的答案提供了额外的上下文,对于那些最初可能很难理解这里发生的事情的人(包括我!和其他人,基于对该答案的评论)。


It's very easy to fall into the trap of thinking that async must be part of the signature of any asynchronous method.很容易陷入认为async必须是任何异步方法签名的一部分的陷阱。 It looks as if it must be;看起来必须如此; it (misleadingly!) reads as if it's whole purpose is to mark a method as asynchronous.它(具有误导性!)读起来好像它的全部目的是将方法标记为异步。

But it's not, Task or Task<T> are required, but not async .但这不是, TaskTask<T>是必需的,但不是async This is shown in @ReedCopsey's answer and in the following correct example (slightly adapted from this useful SO answer ):这显示在@ReedCopsey 的答案和以下正确示例中(略微改编自这个有用的 SO 答案):

public Task<int> MethodTaskAsync(int arg0, int arg1)
{
    Task<int> task = new Task<int>(() => Method(arg0, arg1));
    task.Start(); // Hot task (started task) should always be returned.
    return task;
}

That's why interface method signatures don't need, and can't have, the async keyword: an 'asynchronous' method per se, without regard to how it might be implemented, is just a method that returns a started (and, possibly, already finished) Task or Task<T> .这就是为什么接口方法签名不需要也不能有async关键字:一个“异步”方法本身,不管它是如何实现的,它只是一个返回 start 的方法(并且,可能,已经完成) TaskTask<T>

If async doesn't mark a method as asynchronous, what does it do?如果async没有将方法标记为异步,它会做什么? It's a way to write asynchronous methods more simply: once you have applied it to a method, you can use the await keyword to tell the compiler to correctly handle subsidiary asynchronous calls for you very simply (without it, you could try to handle subsidiary Task s manually, using lots more code like that in the code block above, but to do so would be very complex and error prone).这是一种更简单地编写异步方法的方法:一旦将其应用于方法,就可以使用await关键字非常简单地告诉编译器为您正确处理辅助异步调用(没有它,您可以尝试处理辅助Task s 手动,在上面的代码块中使用更多类似的代码,但这样做会非常复杂且容易出错)。

So if you just want to return a do-nothing, already-completed task from an 'asynchronous' (ie Task -returning) method, you can and should do so synchronously(!), as in @ReedCopsey 's answers, using Task.CompletedTask or Task.FromResult(...) .因此,如果您只想从“异步”(即Task -returning)方法返回一个无所事事的、已经完成的任务,您可以并且应该同步地这样做(!),就像在 @ReedCopsey 的答案中一样,使用Task.CompletedTaskTask.FromResult(...)

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

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