在我的生产者-消费者应用程序中。我有:
CancellationTokenSource cTokenSource = new CancellationTokenSource();
CancellationToken cToken = new CancellationToken();
cToken = cTokenSource.Token;
单击开始按钮,应用程序正在运行。
private async void Start_Click(object sender, RoutedEventArgs e)
{
var producer = Producer();
var consumer = Consumer();
await Task.WhenAll(producer, consumer);
}
在消费者中,我使用了TPL。
async Task Consumer()
{
try
{
var executionDataflowBlockOptions = new ExecutionDataflowBlockOptions
{
MaxDegreeOfParallelism = 50,
CancellationToken = cToken
};
var consumerBlock = new ActionBlock<AppointmentReminder>(
remainder =>
{
// blah blah for long running processes and updating UI
var result = Run(reminder);
},
executionDataflowBlockOptions);
bufferBlock.LinkTo(
consumerBlock, new DataflowLinkOptions { PropagateCompletion = true });
await Task.Delay(500);
}
现在,我有一个取消按钮,我想在单击时停止TPL使用者任务。怎么样?
private void Cancel_Click(object sender, RoutedEventArgs e)
{
最佳答案
.Net中的取消是合作的。您创建一个CancellationTokenSource
来处理取消,并使用CancellationToken
通知取消。要取消令牌,只需调用CancellationTokenSource.Cancel
:
cTokenSource.Cancel();
顺便说一句,直接创建
CancellationToken
没什么用,因为它永远无法取消。您应该从CancellationTokenSource
获得令牌:var cTokenSource = new CancellationTokenSource();
var cToken = cTokenSource.Token;