异步事件处理程序通过事件参数回调

时间:2016-04-16 07:58:38

标签: c# events asynchronous

当我需要收集通过包含异步调用的事件hadnler更改的事件参数数据时,我遇到了问题。正如您在下面的代码中看到的,MessageReceiver会引发事件并从属性"更改"中收集数据,并继续处理。问题是当事件处理程序是异步的时,因为它使用" await"来调用asny方法。在方法OnMyEvent代码在调用处理程序后立即继续,它不会等待处理程序完成,所以"更改"属性没有设置......如何让事情更多"同步"?

public class MyEventArgs:EventArgs
{
    public bool Change { get; set; }
}

public delegate void MyEventHandler(object sender, MyEventArgs e);

public class MessageReceiver
{
    public event MyEventHandler MyEvent;

    public void RaiseEvent()
    {
        OnMyEvent();
    }

    protected void OnMyEvent()
    {
        MyEventArgs e = new MyEventArgs();
        if (MyEvent != null)
            MyEvent(this, e);
        if (e.Change)
            Console.WriteLine("Change occured");
    }
}
public class Form
{
    MessageReceiver mr;
    public Form(MessageReceiver MR)
    {
        mr = MR;
        mr.MyEvent += Mr_MyEvent;
    }

    private async void Mr_MyEvent(object sender, MyEventArgs e)
    {
        string s = await GetString();
        e.Change = true;
    }

    public async Task<string> GetString()
    {
        return await Task.Factory.StartNew(() =>
        {
            return Guid.NewGuid().ToString();
        }
            );
    }
}
public class Program
{
    static void Main(string[] args)
    {
        MessageReceiver mr = new MessageReceiver();
        Form frm = new Form(mr);
        mr.RaiseEvent();
    }
}

1 个答案:

答案 0 :(得分:2)

我在博客上讨论a variety of approaches for asynchronous events。我推荐使用延迟方法,您可以使用DeferralManager中的IDeferralSourceNito.AsyncEx.Coordination library类型来实现:

web.authorize_security_group_egress('test', 'tcp', from_port=5984, to_port=5984, cidr_ip='0.0.0.0/0')