繁体   English   中英

关闭 wpf window 时如何判断 await 是否正在运行或已完成运行

[英]How do I tell if await is running or has finished running when closing wpf window

我正在运行异步等待模式。
为什么线程运行等于等待的变量仍然是 null 直到它完成我发现。
我认为这将是一项任务,例如有一个 class 变量定义为

IXPubMagickServiceCompareOutputModel _results = null;

它是等于 async 方法中的 await 的变量

 _results = await CompareImageServiceAsync(inputModel, progress,
                       PrintImagesAsyncCommand.CancellationTokenSource.Token)
                    .ConfigureAwait(false);

当这行可能和等待线程正在运行时,会处理 window 关闭甚至处理。 在此事件句柄中, _results变量是 null,而等待线程仍在运行。
这是为什么? 我想我可以将_results转换为相应的任务

var resultsTask = (Task<IXPubMagickServiceCompareOutputModel>)_results;

但我不能,因为等待任务运行时_result变量仍然是 null

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM