【问题标题】:How do I tell if await is running or has finished running when closing wpf window关闭 wpf 窗口时如何判断 await 是否正在运行或已完成运行
【发布时间】:2021-06-11 17:00:02
【问题描述】:

我正在运行异步等待模式。
为什么线程正在运行等于等待的变量仍然为空,直到它完成我找到了。
我还以为是任务 例如有一个类变量定义为

IXPubMagickServiceCompareOutputModel _results = null;

它是与异步方法中的等待相等的变量

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

当这行可能和等待线程正在运行时,一个窗口关闭甚至被处理。 在这种情况下,当等待线程仍在运行时,_results 变量为空。
这是为什么? 我以为我可以将_results 转换为相应的任务

var resultsTask = (Task<IXPubMagickServiceCompareOutputModel>)_results;

但我不能,因为在 await 任务运行时,_result 变量仍然为空

【问题讨论】:

  • 在您的 OnClosing 事件处理程序中调用 PrintImagesAsyncCommand.CancellationTokenSource.Cancel()
  • await 不运行,它等待一个已经活动的任务在没有阻塞的情况下完成,并返回结果(如果有)。您发布的代码IXPubMagickServiceCompareOutputModel _results 表明_results 根本不是一个任务,而是一个IXPubMagickServiceCompareOutputModel 值。
  • 您的帖子将受益于一些编辑。
  • 本例中的任务是CompareImageServiceAsync()返回的任务。

标签: c# async-await task-parallel-library


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2010-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-06
    • 1970-01-01
    • 1970-01-01
    • 2011-11-14
    相关资源
    最近更新 更多