繁体   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