通常,当您尝试在视图模型中执行异步任务时,代码看起来像这样(简化):
public class MyViewModel
{
private CancellationTokenSource CTS { get; set; }
public async Task Process()
{
CTS = new CancellationTokenSource();
try
{
await LongRunningTask(CTS.Token);
} catch (OperationCanceledException) { }
}
public async Task Cancel()
{
CTS.Cancel();
}
}
问题是CancellationTokenSource
是IDisposable
。这是否意味着我们只是将其放在using
块中,或者是否存在更多内容,因为它存储在私有属性中?