Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
350 views
in Technique[技术] by (71.8m points)

c# - 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();

What happens to exceptions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First of all, Start() only works on the (very rare) Tasks 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.

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);
}

If you do this, any exception from the Send() method will end up in the returned 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().

Also, depending on the type of _mq, consider using SendAsync(), if something like that is available.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...