我正在研究一個應用程序,其中有一個可以停止的任務&稍後重新啓動。 的,我已經兩個方法:如何在C中重新啓動System.Threading.Tasks.Task#
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();
}
}
}
目前,我創建任務和的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");
}
}
謝謝你的幫助。
如果我每次重新啓動時都重新創建新實例,這對內存來說還不夠嗎? – Younes 2014-10-02 13:33:20
@cYounes是什麼讓你這樣想? – 2014-10-02 13:36:19
,因爲這段代碼將在一個服務中永久運行,並且要確保它不會產生任何錯誤:) – Younes 2014-10-02 13:41:24