延迟然后执行任务 [英] Delay then execute Task
问题描述
快速提问,我想等待一秒钟,然后再启动一个没有返回值的异步任务。
这是正确的方法吗?
Quick question, I want to wait a second before launching an async task without a return value.
Is this the right way to do it?
Task.Delay(1000)
.ContinueWith(t => _mq.Send(message))
.Start();
例外情况如何?
推荐答案
首先, Start()
仅适用于(非常罕见)的 Task
Task 构造函数创建的>(例如 new Task(()=> _mq.Send(message))
)。在所有其他情况下,它将引发异常,因为 Task
已启动或正在等待另一个 Task
。
First of all, Start()
only works on the (very rare) Task
s that were created using the Task
constructor (e.g. new Task(() => _mq.Send(message))
). In all other cases, it will throw an exception, because the Task
is already started or waiting for another Task
.
现在,可能最好的方法是将代码放入单独的 async
方法中并使用等待
:
Now, probably the best way to do this would be to put the code into a separate async
method and use await
:
async Task SendWithDelay(Message message)
{
await Task.Delay(1000);
_mq.Send(message);
}
如果这样做, Send中的任何例外()
方法将最终返回到返回的 Task
。
If you do this, any exception from the Send()
method will end up in the returned Task
.
不想这样做,使用 ContinueWith()
是一种合理的方法。在这种情况下,例外是从 ContinueWith()
返回的 Task
。
If you don't want to do that, using ContinueWith()
is a reasonable approach. In that case, exception would be in the Task
returned from ContinueWith()
.
另外,根据 _mq
的类型,考虑使用 SendAsync()
像这样可用。
Also, depending on the type of _mq
, consider using SendAsync()
, if something like that is available.
这篇关于延迟然后执行任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!