创建长时间运行任务的最佳实践
本文关键字:最佳 任务 长时间 运行 创建 | 更新日期: 2023-09-27 18:12:44
对于需要在。net 4中使用Task API运行的后台线程来说,这是一个好的设计吗?我唯一担心的是如果我们想取消这个任务我该怎么做?我知道我可以将ProgramEnding
设置为true
,但我知道在任务API中有一个CancellationToken
。
这只是一个示例代码示例,以便一个线程将添加到集合中,另一个线程将从中删除。任务设置为长运行,因为它需要在程序运行时连续运行
private void RemoveFromBlockingCollection()
{
while (!ProgramEnding)
{
foreach (var x in DataInQueue.GetConsumingEnumerable())
{
Console.WriteLine("Task={0}, obj={1}, Thread={2}"
, Task.CurrentId, x + " Removed"
, Thread.CurrentThread.ManagedThreadId);
}
}
}
private void button1_Click(object sender, EventArgs e)
{
DataInQueue = new BlockingCollection<string>();
var t9 = Task.Factory.StartNew(RemoveFromBlockingCollection
, TaskCreationOptions.LongRunning);
for (int i = 0; i < 100; i++)
{
DataInQueue.Add(i.ToString());
Console.WriteLine("Task={0}, obj={1}, Thread={2}",
Task.CurrentId, i + " Added",
Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(100);
}
ProgramEnding = true;
}
UPDATE:我发现我可以删除ProgramEnding布尔值并使用DataInQueue。
正如您已经提到的,您可以使用CancellationToken。这样做:
var cancellationTokenSource = new CancellationTokenSource();
Task.Factory.StartNew(RemoveFromBlockingCollection
, TaskCreationOptions.LongRunning
, cancellationTokenSource.Token);
在你的代码后面,你可以取消任务:
cancellationTokenSource.Cancel();
在长时间运行的任务中,如果请求取消,您可以请求令牌:
if (cancellationTokenSource.Token.IsCancellationRequested)