删除内联静态事件
我在静态方法中有一个静态事件,我暂时附加到该静态事件,因为我不希望它保留在内存中,或者如果我调用它两次,我就会触发两个事件处理程序。
我对这些是否应该是静态的没有什么发言权,并且不想承担讨论/重构的责任。
最初我是这样做的,
public static void DoSomething()
{
try
{
MyStaticClass.MyEvent +=new EventHandler<HandledEventArgs>(MyStaticClass_HandleMe);
... //Doing Stuff
}
finally
{
MyStaticClass.MyEvent -=new EventHandler<HandledEventArgs>(MyStaticClass_HandleMe);//Detach from event
}
}
这一直工作得很好,但我想内联处理事件,以便与方法中的另一个事件保持一致,以及设置一个函数本地的取消布尔值并由另一个事件。
public static void DoSomething()
{
try
{
bool cancel = false;
MyStaticClass.MyEvent +=new EventHandler<HandledEventArgs>(delegate(object sender, HandledEventArgs e)
{
cancel = true;
})
... //Doing Stuff dependent on cancel = false;
}
finally
{
//???
}
}
我的问题是,在场景 2 中,如何清理并脱离静态事件?
I have a static event in a static method that I am temporarily attaching to, as I don't want it to hang around in memory, or get in a situation where I am firing two event handlers if I call it twice.
I have little say in whether these should be static or not, and would prefer not to have the discussion / refactor responsibility.
Initially I was doing it like this
public static void DoSomething()
{
try
{
MyStaticClass.MyEvent +=new EventHandler<HandledEventArgs>(MyStaticClass_HandleMe);
... //Doing Stuff
}
finally
{
MyStaticClass.MyEvent -=new EventHandler<HandledEventArgs>(MyStaticClass_HandleMe);//Detach from event
}
}
This has been working fine, but I would like to handle the event inline, to be consistent with another event in the method, as well as setting a cancel boolean that is local to the function and being used by the other event.
public static void DoSomething()
{
try
{
bool cancel = false;
MyStaticClass.MyEvent +=new EventHandler<HandledEventArgs>(delegate(object sender, HandledEventArgs e)
{
cancel = true;
})
... //Doing Stuff dependent on cancel = false;
}
finally
{
//???
}
}
My question is, in scenario 2, how can I clean up and detach from the static event?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你可以尝试这样的事情:
You could try something like this:
请参阅此线程了解一个很好的方法。
基本上,只需将内联方法存储在委托中即可,并在最后取消订阅。
See this thread for a great approach.
Basically, just store your inlined method in a delegate, and unsubscribe it during your finally.