【发布时间】:2016-03-09 08:27:27
【问题描述】:
我使用 C#、.NET Framework 4.5、VS2015。
我为由黑盒模块触发的事件 (TcpRequest) 实现了一个事件处理程序。 我的事件处理程序调用一个私有方法,该方法向客户端/GUI 触发事件并等待用户的响应。 同时,黑盒模块不断触发 TcpRequest 事件。不知何故,我需要在等待时对传入事件进行排队。 一旦用户对第一个事件做出响应,队列就可以“刷新”。
这种情况是否有任何设计模式或最佳实践(在等待用户响应时排队)?我需要使用 await 什么的吗?
以下是我的代码。请随时修改它们。提前谢谢你。
public void TcpRequestHandler(int id, CONN_INFO connInfo)
{
if (SomeCondition)
{
var myArgs = new MyEventArgs()
{
Id = id,
ConnInfo = connInfo
}
// this the way I tried and I know it is wrong,
// because it always fires event without "waiting in queue"
lock (_eventQueue)
{
_eventQueue.Add(myArgs);
}
FireEventToClient(myArgs);
}
}
private void FireEventToClient(MyEventArgs myArgs)
{
EventToClient(this, myArgs);
if (myArgs.Continue)
{
// "flush" the event queue
...
// do other things
...
}
}
public class MyEventArgs : EventArgs
{
public int Id {get; private set;}
public CONN_INFO ConnInfo {get; private set;}
public bool Continue {get; set;}
}
【问题讨论】:
标签: c# .net events design-patterns