【发布时间】:2014-10-02 13:23:38
【问题描述】:
我正在开发一个应用程序,其中我有一个可以在以后停止和重新启动的任务。 为此我有两种方法:
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");
}
}
感谢您的帮助。
【问题讨论】:
标签: c# .net multithreading task