简体   繁体   English

没有等待的异步任务的第二次实现

[英]Second implementation of async task without await

What can I do when I have an interface that returns a task (void) but one of the implementations has no async action?当我有一个返回任务(void)的接口但其中一个实现没有异步操作时,我该怎么办?

My interface IDatabaseService has two implementations: FirestoreDatabaseService and CacheDatabaseService .我的接口IDatabaseService有两个实现: FirestoreDatabaseServiceCacheDatabaseService It makes sense for FirestoreDatabaseService to use the Method async Task AddResult(ResultDto result) as result of a method but the CacheDatabaseService has only a list and needs no await, it is basically a void method. FirestoreDatabaseService使用 Method async Task AddResult(ResultDto result)作为方法的结果是有意义的,但CacheDatabaseService只有一个列表并且不需要等待,它基本上是一个 void 方法。

I get a warning "Warning CS1998 This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)'" when I implement the method in CacheDatabaseService async.我收到警告“警告 CS1998 此异步方法缺少 'await' 运算符,将同步运行。考虑使用 'await' 运算符等待非阻塞 API 调用或 'await Task.Run(...)'”当我在 CacheDatabaseService 异步中实现该方法。 If I remove the async I have to return a task but Task.FromResult does not work for void Tasks.如果我删除异步我必须返回一个任务,但 Task.FromResult 不适用于 void 任务。

That warning almost always means your method should not be async .该警告几乎总是意味着您的方法不应该是async

The async keyword really just enables the use of await . async关键字实际上只是允许使用await So if you aren't using await , you don't need async .因此,如果您不使用await ,则不需要async

If AddResult must return a Task , then return a Task .如果AddResult必须返回一个Task ,则返回一个Task If you aren't actually doing anything asynchronous, then you can return Task.CompletedTask .如果您实际上没有做任何异步操作,那么您可以返回Task.CompletedTask

For example:例如:

public Task AddResult(ResultDto result) {
    ...
    return Task.CompletedTask;
}

If you have to return a value ( Task<T> ), then you can use Task.FromResult() .如果您必须返回一个值( Task<T> ),那么您可以使用Task.FromResult()

An interface that specifies that a method should return a Task is just a way of making it possible to make the method async .指定方法应返回Task的接口只是使方法成为可能的一种方式async It doesn't mean it must.这并不意味着它必须。

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

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