首页 > 解决方案 > 关闭 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在等待任务运行时变量仍然为空

标签: c#async-awaittask-parallel-library

解决方案


我想你想要的是使用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)
    }
}


推荐阅读