簡體   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