【发布时间】:2020-01-10 12:33:02
【问题描述】:
在我的代码中,我在单击 LoadTemplated 按钮时从 excel 下载数据。 我想在用户单击“取消”按钮后立即取消下载。 不知何故,任务在继续时没有被取消。 需要关于我在这里做错了什么的建议。
public CheckListDetailViewModel(IAuditInspectionDataService auditInspectionDataService)
{
_auditInspectionDataService = auditInspectionDataService;
LoadChecklistTemplateCommand = new DelegateCommand(OnLoadTemplate, CanLoadTemplate).ObservesProperty(() => ChecklistItems.Count);
}
private CancellationTokenSource cts;
private async void OnLoadTemplate()
{
try
{
if (cts != null)
{
cts.Cancel();
}
else
{
cts = new CancellationTokenSource();
IsBusy = true;
LoadTemplateButtonValue = "Cancel";
var items = await Task.Run(() =>
{
if (cts.Token.IsCancellationRequested)
cts.Token.ThrowIfCancellationRequested();
var checklistItems = _auditInspectionDataService.GetCheckList(InspectionType.InspectionTypeId);
return checklistItems;
}, cts.Token);
LoadTemplateButtonValue = "Load Template";
ChecklistItems = new ObservableCollection<ChecklistItem>(items);
}
}
catch (Exception ex)
{
IsBusy = false;
LoadTemplateButtonValue = "Load Template";
ChecklistItems = null;
cts = null;
Debug.WriteLine(ex);
}
finally
{
IsBusy = false;
LoadTemplateButtonValue = "Load Template";
//cts.Dispose();
}
}
【问题讨论】:
-
您的代码有几个问题,但最重要的是 _auditInspectionDataService.GetCheckList 不可取消或您没有传递 CancellationToken
-
据我了解,Task.Run 中的代码只会在启动时检查是否取消,如果稍后请求取消,则不会实际取消任务。
-
是的,任务开始后由您来检查是否取消
-
@Sir Rufo 我也尝试过这样做,并在服务中通过了 cancelllationt 令牌,但它仍然不起作用。
-
顺便说一句:如果您为 cts 分配一个新实例并且任务将检查 cts.Token.IsCancellationRequested,会发生什么?它将在新创建的 CancellationTokenSource 上执行此操作
标签: c# wpf asynchronous mvvm async-await