当我需要收集事件处理程序中包含异步调用的已更改事件参数数据时,我遇到了问题。如下面的代码所示,MessageReceiver引发事件并从属性“Change”收集数据,然后继续处理。问题在于当事件处理程序是异步的时,它会调用带有“await”的异步方法。在OnMyEvent方法中,调用处理程序后代码立即继续执行,不等待处理程序完成,因此“Change”属性未设置...如何使事情更加“同步”?
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();
}
}