gpt4 book ai didi

c# - 如何等待引发 C# 事件?

转载 作者:太空狗 更新时间:2023-10-29 17:41:06 28 4
gpt4 key购买 nike

我有一个 Sender 类,它在 IChannel 上发送一个 Message:

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 事件发送的 Message 类型做出响应。事件参数包含感兴趣的消息。

我希望 Sender.Send() 方法等待一小段时间以查看是否引发此事件。如果是这样,我将返回其 MessageEventArgs.Message 属性。如果不是,我将返回一个空的 Message

我怎么能这样等呢?我不希望使用 ManualResetEvents 等进行线程处理,因此坚持使用常规 event 对我来说是最佳选择。

最佳答案

使用 AutoResetEvent

给我几分钟时间,我会整理一个样本。

这里是:

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# - 如何等待引发 C# 事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2820870/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com