如何提高C#事件? [英] How do I wait for a C# event to be raised?
问题描述
我有一个发件人
类,发送消息
在 IChannel
:
public class MessageEventArgs : EventArgs {
public Message Message { get; private set; }
public MessageEventArgs(Message m) { Message = m; }
}
public interface IChannel {
public event EventHandler<MessageEventArgs> MessageReceived;
void Send(Message m);
}
public class Sender {
public const int MaxWaitInMs = 5000;
private IChannel _c = ...;
public Message Send(Message m) {
_c.Send(m);
// wait for MaxWaitInMs to get an event from _c.MessageReceived
// return the message or null if no message was received in response
}
}
当我们发送消息时, ICHannel
有时会根据通过提高 MessageReceived
事件发送了什么样的消息
。事件参数包含感兴趣的消息。
When we send messages, the IChannel
sometimes gives a response depending on what kind of Message
was sent by raising the MessageReceived
event. The event arguments contain the message of interest.
我想要 Sender.Send()
方法等待一个短时间来看看这个事件是否提高。如果是这样,我将返回其 MessageEventArgs.Message
属性。如果没有,我返回一个null 消息
。
I want Sender.Send()
method to wait for a short time to see if this event is raised. If so, I'll return its MessageEventArgs.Message
property. If not, I return a null Message
.
我怎么能这样等待?我不喜欢用 ManualResetEvents
做线程工作,所以坚持定期的事件
将是
How can I wait in this way? I'd prefer not to have do the threading legwork with ManualResetEvents
and such, so sticking to regular event
s would be optimal for me.
推荐答案
使用 AutoResetEvent
。
Gimme几分钟,我会一起捡样本。
Gimme a few minutes and I'll throw together a sample.
这是:
public class Sender
{
public static readonly TimeSpan MaxWait = TimeSpan.FromMilliseconds(5000);
private IChannel _c;
private AutoResetEvent _messageReceived;
public Sender()
{
// initialize _c
this._messageReceived = new AutoResetEvent(false);
this._c.MessageReceived += this.MessageReceived;
}
public Message Send(Message m)
{
this._c.Send(m);
// wait for MaxWaitInMs to get an event from _c.MessageReceived
// return the message or null if no message was received in response
// This will wait for up to 5000 ms, then throw an exception.
this._messageReceived.WaitOne(MaxWait);
return null;
}
public void MessageReceived(object sender, MessageEventArgs e)
{
//Do whatever you need to do with the message
this._messageReceived.Set();
}
}
这篇关于如何提高C#事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!