难道Task.Wait(INT)停止,如果超时时间的任务,而无需在任务结束?任务、结束、时间、Task

2023-09-02 10:30:19 作者:可惜卟是迩

我有一个任务,我希望它采取在第二运行,但如果它花费的时间超过几秒钟,我想取消该任务。

I have a task and I expect it to take under a second to run but if it takes longer than a few seconds I want to cancel the task.

例如:

Task t = new Task(() =>
        {
            while (true)
            {
                Thread.Sleep(500);
            }
        });
t.Start();
t.Wait(3000);

请注意,3000毫秒等待到期后。当时的任务取消,当超时到期或任务仍在运行?

Notice that after 3000 milliseconds the wait expires. Was the task canceled when the timeout expired or is the task still running?

推荐答案

如果您想取消工作,你应该通过在的CancellationToken 当你创建任务。这将允许你取消工作从外面。如果你愿意,你可以取消绑到一个计时器。

If you want to cancel a Task, you should pass in a CancellationToken when you create the task. That will allow you to cancel the Task from the outside. You could tie cancellation to a timer if you want.

要创建任务与取消标记看到这样的例子:

To create a Task with a Cancellation token see this example:

var tokenSource = new CancellationTokenSource();
var token = tokenSource.Token;

var t = Task.Factory.StartNew(() => {
    // do some work
    if (token.IsCancellationRequested) {
        // Clean up as needed here ....
    }
    token.ThrowIfCancellationRequested();
}, token);

要取消工作呼叫取消() tokenSource

 
精彩推荐
图片推荐