[英]How do I make sure no handlers are attached to an event?
I am adding an event handler like this: 我正在添加这样的事件处理程序 :
theImage.MouseMove += new MouseEventHandler(theImage_MouseMove);
but in my application, this code gets run every time the page is shown, so I want to attach the event handler only once , but how can I tell if a handler has been set yet or not, something like this: 但是在我的应用程序中, 每次显示页面时都会运行此代码,因此我只想附加一次事件处理程序,但是如何确定是否设置了处理程序,如下所示:
if(theImage.MouseMove == null) //error
theImage.MouseMove += new MouseEventHandler(theImage_MouseMove);
I might me missing something, but if you just want to make sure that the handle is only called once, why don't you use -=
before adding it. 我可能会遗漏一些东西,但是如果您只想确保该句柄仅被调用一次,为什么在添加它之前不使用
-=
。 Something like this: 像这样:
public static void Main(string[] args)
{
var timer = new Timer(1000);
timer.Elapsed -= new ElapsedEventHandler(timer_Elapsed);
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
timer.Elapsed -= new ElapsedEventHandler(timer_Elapsed);
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
timer.Start();
System.Threading.Thread.Sleep(4000);
}
static void timer_Elapsed(object sender, ElapsedEventArgs e)
{
Console.WriteLine("Hit!");
}
The handler will only run once every second. 处理程序仅每秒运行一次。
You can shorten it down if you only want to attach once: 如果您只想附加一次,可以将其缩短:
theImage.MouseMove -= theImage_MouseMove; //If it wasn't attached, doesn't matter
theImage.MouseMove += theImage_MouseMove;
I'm not sure if this is the best solution, but the way I usually do this is to simply use an unsubscribe before the subscribe. 我不确定这是否是最好的解决方案,但是我通常这样做的方法是在订阅之前简单地使用取消订阅。
If you do something like: 如果您执行以下操作:
TheImage.MouseMove -= new MouseEventHandler(theImage_MouseMove);
TheImage.MouseMove += new MouseEventHandler(theImage_MouseMove);
It will only ever get added once. 它只会被添加一次。 If it doesn't already exist (the first time it's triggered), the -= doesn't hurt anything if it hasn't been subscribed to previously.
如果尚不存在(首次触发),则-=不会损害任何内容,前提是之前未订阅过。
theImage.MouseMove.GetInvocationList().Length
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.