c# - 关闭 wpf 窗口时如何判断 await 是否正在运行或已完成运行
问题描述
我正在运行异步等待模式。
为什么线程正在运行等于等待的变量仍然为空,直到它完成我发现。
我认为这将是一项任务,例如有一个类变量定义为
IXPubMagickServiceCompareOutputModel _results = null;
它是等于 async 方法中的 await 的变量
_results = await CompareImageServiceAsync(inputModel, progress,
PrintImagesAsyncCommand.CancellationTokenSource.Token)
.ConfigureAwait(false);
当这行可能和等待线程正在运行时,甚至会处理一个窗口关闭。在此事件句柄中,_results
当等待线程仍在运行时,变量为空。
这是为什么?我以为我可以将其_results
转换为相应的任务
var resultsTask = (Task<IXPubMagickServiceCompareOutputModel>)_results;
但我不能因为_result
在等待任务运行时变量仍然为空
解决方案
我想你想要的是使用CancellationToken
.
像这样:
class MyWpfWindow // or MVVM ViewModel
{
protected override void OnClosing()
{
CancellationTokenSource cts = this.PrintImagesAsyncCommand.CancellationTokenSource; // Create a local reference copy to avoid race-conditions.
if( cts != null ) cts.Cancel();
}
private async Task DoSomethingAsync()
{
IXPubMagickServiceCompareOutputModel results;
try
{
CancellationToken ct = this.PrintImagesAsyncCommand.CancellationTokenSource.Token;
results = await this.CompareImageServiceAsync( inputModel, progress, ct );
// Don't use `ConfigureAwait(false)` in WPF UI code!
}
catch( OperationCanceledException )
{
// The `OnClosing` event was invoked while `CompareImageServiceAsync` was running, so just return immediately and don't let the `OperationCanceledException` escape.
return;
}
// (Do stuff with `results` here)
}
}
推荐阅读
- javascript - 如何在访问 REST API 时修复 ANGULAR 中的授权问题
- python - docusign-python-api 错误:PARTNER_AUTHENTICATION_FAILED
- python - Pandas - 从 excel 中读取表格
- spring-boot - 基于 docker 环境变量切换 spring 配置文件不起作用
- jquery - 如何从链接单击添加数据到表单字段
- node.js - 如何根据另一个 JSON 对象中的字符串为 JSON 对象选择键值
- ruby-on-rails - 当更改的属性在“回调后”中是干净的时,如何依赖脏模型?
- scala - 将 HiveQL 转换为 Spark Scala
- push-notification - 应用客户端如何处理传入的即时消息和通知?
- html - 在不退出 tr 的情况下在表中创建新行