而无需在任务结束

而无需在任务结束

本文介绍了难道Task.Wait(INT)停止,如果超时时间的任务,而无需在任务结束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这篇关于难道Task.Wait(INT)停止,如果超时时间的任务,而无需在任务结束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 03:26