簡體   English   中英

用於等待事件處理程序的 AsyncEx DeferralManager

[英]AsyncEx DeferralManager for awaiting event handlers

我在這個線程中有一個類似的問題,根據 Stephen Cleary 的評論,WinRT 的解決方案是使用延遲。 線程中指出的解決方案也適用於我,但我想嘗試使用延遲,因為它可能是或成為處理這種情況的標准方式。

所以我閱讀了他關於它的 博客並試圖將它應用到我的代碼中,但我似乎無法讓它工作。 發生的事情是尚未等待事件訂閱。 我也找不到任何可以運行和分析的完整示例程序。 所以我嘗試創建一個示例控制台程序來演示我看到的問題。

首先,我有事件處理程序委托和事件參數定義:

public delegate void CancelEventHandlerAsync(object sender, CancelEventArgsAsync e);

public class CancelEventArgsAsync : CancelEventArgs
{
    private readonly DeferralManager _deferrals = new DeferralManager();

    public IDisposable GetDeferral()
    {
        return this._deferrals.GetDeferral();
    }

    public Task WaitForDefferalsAsync()
    {
        return this._deferrals.SignalAndWaitAsync();
    }
}

然后是事件發送者的子模塊定義:

public class ChildModule1
{
    public event CancelEventHandlerAsync ChildModuleLaunching;

    public async Task Launch()
    {
         var cancelEventArgs = new CancelEventArgsAsync();
         this.ChildModuleLaunching(this, cancelEventArgs);
         cancelEventArgs.WaitForDefferalsAsync();
         if (cancelEventArgs.Cancel) 
         {
             return;
         }

         Console.WriteLine("Child module 1 launched."); // This should not be executed.
     }
}

然后是訂閱子模塊事件的父類:

public class Parent
{
    private ChildModule1 child1 = new ChildModule1();

    public Parent()
    {
        this.child1.ChildModuleLaunching += this.OnChildModule1Launching;
    }

    public async Task Process()
    {
        await this.child1.Launch();
    }

    private async void OnChildModule1Launching(object sender, CancelEventArgsAsync e)
    {
        var deferral = e.GetDeferral();

        await Task.Delay(2500); // Simulate processing of an awaitable task.
        e.Cancel = true;

        deferral.Dispose();
    }
}

最后,控制台應用程序入口點:

static void Main(string[] args)
{
    var parent = new Parent();

    parent.Process().Wait();

    Console.ReadKey();
}

您需要await WaitForDefferalsAsync調用:

await cancelEventArgs.WaitForDefferalsAsync();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM