有没有办法指定处理已注册事件委托(delegate)的顺序或优先级?例如,我有一个事件,我想在任何其他事件之前立即处理,但我希望其他对象也被允许注册该事件的监听器。如何实现?
假设我希望 proc1 始终在 proc 2 之前运行。
class MessageProcessor
{
private DataClient Client;
public MessageProcesser(DataClient dc)
{
Client = dc;
Client.MessageReceived += ProcessMessage;
}
void proc1(MessageEventArgs e)
{
// Process Message
}
}
class DataClient
{
public event MessageReceievedHandler MessageReceived;
}
void main()
{
DataClient dc = new DataClient();
MessageProcessor syncProcessor = new MessageProcessor(dc); // This one is high priority and needs to process all sync immediately when they arrive before any data messages
MessageProcessor dataProcessor= new MessageProcessor(dc); // This one can process the data as it has time when sync messages are not being processed.
// do other stuff
}
这样做的原因是,我有一个通过 UDP 流发送消息的服务器。它将在数据突发之前发送同步消息。我意识到当收到同步消息时,两个处理程序都会触发,但为了减少延迟,我希望在 dataProcessor 事件之前处理 syncProcessor 对象事件。这将减少正在处理的同步消息的延迟。
此外,我团队中的其他人可能也想注册事件以处理特定消息。他们可能有自己的对象来注册事件(可能不是 MessageProcessor),即使同步消息仍应具有尽可能低的延迟。
EDIT 通过更好的示例使目标更加清晰。
最佳答案
当您多次订阅一个事件时,无法确定事件触发时处理程序的执行顺序。
根据 this answer ,订阅顺序中的顺序,但正如帖子作者所说,这是一个实现细节,您不能依赖它。
您当然可以编写自己的“事件管理器”(参见下面的示例)以已知顺序执行您的处理程序,但我认为这不是一个好主意。也许您应该重新设计您的事件以删除您的要求。
public class MyClass
{
// Could be anything...
public delegate void MyEventHandler(object sender, EventArgs e);
public event MyEventHandler TestEvent;
public void Test()
{
if (this.TestEvent != null)
{
this.TestEvent(this, EventArgs.Empty);
}
}
}
public class EventManager
{
private List<EventHandler> Handlers = new List<EventHandler>();
public void AddHandler(EventHandler handler)
{
this.Handlers.Add(handler);
}
public void RemoveHandler(EventHandler handler)
{
this.Handlers.Remove(handler);
}
public void Handler(object sender, EventArgs e)
{
foreach (var z in this.Handlers)
{
z.Invoke(sender, e);
}
}
}
private static void Main(string[] args)
{
MyClass test = new MyClass();
EventManager eventManager = new EventManager();
// Subscribes to the event
test.TestEvent += eventManager.Handler;
// Adds two handlers in a known order
eventManager.AddHandler(Handler1);
eventManager.AddHandler(Handler2);
test.Test();
Console.ReadKey();
}
private static void Handler1(object sender, EventArgs e)
{
Console.WriteLine("1");
}
private static void Handler2(object sender, EventArgs e)
{
Console.WriteLine("2");
}
关于c# - 事件优先级和流程顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9622614/