我正在开发一个应用程序,其中的任务可以稍后停止并重新启动。 为此我有两种方法:
public static void TaskProcess()
{
var tokenSource = new CancellationTokenSource();
CancellationToken token = tokenSource.Token;
var task = new Task(
() =>
{
DoWork(token);
},
token);
task.ContinueWith(
task1 =>
{
Console.WriteLine("Task finished... press any key to continue");
Console.ReadKey();
Console.WriteLine("Press q to quit...");
},
token);
task.Start();
string input;
while ((input = Console.ReadLine()) != "q")
{
if (input == "c")
{
tokenSource.Cancel();
}
if (input == "r")
{
if (task.IsCompleted)
{
// Here i want to restart my completed task
}
else
{
Console.WriteLine("Task is not completed");
}
}
}
}
private static void DoWork(CancellationToken token)
{
int i = 0;
while (true)
{
i++;
Console.WriteLine("{0} Task continue...", i);
Thread.Sleep(1000);
if (token.IsCancellationRequested)
{
Console.WriteLine("Canceling");
token.ThrowIfCancellationRequested();
}
}
}
目前,我创建了 Task 和 CancellationToken 的新实例来“重新启动”任务,但如果可能的话,我正在寻找更好的东西:
if (input == "r")
{
if (task.IsCompleted)
{
Console.WriteLine("Task is completed... Restarting");
tokenSource = new CancellationTokenSource();
token = tokenSource.Token;
CancellationToken token1 = token;
task = new Task(
() => DoWork(token1),
token);
task.Start();
}
else
{
Console.WriteLine("Task is not completed");
}
}
感谢您的帮助。
最佳答案
不,Task
和 TaskCancellationSource
是 use 和 throw 对象。你不能重复使用它们。您必须像当前一样创建新对象。
这是有道理的,假设您已经取消了一个任务
,稍后在某个时刻,一些代码需要检查任务
的状态。在您重新启动任务后不久(不可能,为了解释而说),告诉已经已取消
任务的状态为正在运行
是否会产生误导?
关于c# - 如何在 C# 中重新启动 System.Threading.Tasks.Task,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26161849/