我创建了一个线程安全的类,将 a 绑定CancellationTokenSource
到 a Task
,并保证CancellationTokenSource
在其关联Task
完成时将被释放。它使用锁来确保CancellationTokenSource
在处理期间或处理后不会被取消。发生这种情况是为了遵守文档,该文档指出:
只有在对象上的所有其他操作都已完成Dispose
时,才能使用该方法。CancellationTokenSource
还有:_
该Dispose
方法使CancellationTokenSource
处于不可用状态。
这是课程:
public class CancelableExecution
{
private readonly bool _allowConcurrency;
private Operation _activeOperation;
// Represents a cancelable operation that signals its completion when disposed
private class Operation : IDisposable
{
private readonly CancellationTokenSource _cts;
private readonly TaskCompletionSource<bool> _completionSource;
private bool _disposed;
public Task Completion => _completionSource.Task; // Never fails
public Operation(CancellationTokenSource cts)
{
_cts = cts;
_completionSource = new TaskCompletionSource<bool>(
TaskCreationOptions.RunContinuationsAsynchronously);
}
public void Cancel() { lock (this) if (!_disposed) _cts.Cancel(); }
void IDisposable.Dispose() // It is disposed once and only once
{
try { lock (this) { _cts.Dispose(); _disposed = true; } }
finally { _completionSource.SetResult(true); }
}
}
public CancelableExecution(bool allowConcurrency)
{
_allowConcurrency = allowConcurrency;
}
public CancelableExecution() : this(false) { }
public bool IsRunning => Volatile.Read(ref _activeOperation) != null;
public async Task<TResult> RunAsync<TResult>(
Func<CancellationToken, Task<TResult>> action,
CancellationToken extraToken = default)
{
if (action == null) throw new ArgumentNullException(nameof(action));
var cts = CancellationTokenSource.CreateLinkedTokenSource(extraToken);
using (var operation = new Operation(cts))
{
// Set this as the active operation
var oldOperation = Interlocked.Exchange(ref _activeOperation, operation);
try
{
if (oldOperation != null && !_allowConcurrency)
{
oldOperation.Cancel();
await oldOperation.Completion; // Continue on captured context
// The Completion never fails
}
cts.Token.ThrowIfCancellationRequested();
var task = action(cts.Token); // Invoke on the initial context
return await task.ConfigureAwait(false);
}
finally
{
// If this is still the active operation, set it back to null
Interlocked.CompareExchange(ref _activeOperation, null, operation);
}
}
// The cts is disposed along with the operation
}
public Task RunAsync(Func<CancellationToken, Task> action,
CancellationToken extraToken = default)
{
if (action == null) throw new ArgumentNullException(nameof(action));
return RunAsync<object>(async ct =>
{
await action(ct).ConfigureAwait(false);
return null;
}, extraToken);
}
public Task CancelAsync()
{
var operation = Volatile.Read(ref _activeOperation);
if (operation == null) return Task.CompletedTask;
operation.Cancel();
return operation.Completion;
}
public bool Cancel() => CancelAsync() != Task.CompletedTask;
}
类的主要方法CancelableExecution
是RunAsync
和Cancel
。默认情况下不允许并发操作,这意味着RunAsync
在开始新操作之前,第二次调用将静默取消并等待上一个操作完成(如果它仍在运行)。
此类可用于任何类型的应用程序。虽然它的主要用途是在 UI 应用程序中,在带有用于启动和取消异步操作的按钮的表单内部,或者在每次更改其选定项目时取消和重新启动操作的列表框。以下是第一种情况的示例:
private readonly CancelableExecution _cancelableExecution = new CancelableExecution();
private async void btnExecute_Click(object sender, EventArgs e)
{
string result;
try
{
Cursor = Cursors.WaitCursor;
btnExecute.Enabled = false;
btnCancel.Enabled = true;
result = await _cancelableExecution.RunAsync(async ct =>
{
await Task.Delay(3000, ct); // Simulate some cancelable I/O operation
return "Hello!";
});
}
catch (OperationCanceledException)
{
return;
}
finally
{
btnExecute.Enabled = true;
btnCancel.Enabled = false;
Cursor = Cursors.Default;
}
this.Text += result;
}
private void btnCancel_Click(object sender, EventArgs e)
{
_cancelableExecution.Cancel();
}
该RunAsync
方法接受一个额外的CancellationToken
作为参数,该参数链接到内部创建的CancellationTokenSource
. 提供此可选令牌在高级场景中可能很有用。