Detaching a handler on the first call
I would like to call the event handler just once and then detach it. I tried to write:
EventHandler handler = (s, e) =>
{
// Do something
//
// blabla
// Detach the handler
SizeChanged -= handler;
};
SizeChanged += handler;
However on the line SizeChanged -= handler
I am getting this error
Use of unassigned local variable 'handler'
Do you have an idea of how I should proceed? I was thinking about using a boolean flag, but I'll only do so if I can't find a way to detach the handler.
source to share
This is because he has not yet been appointed. Try to make a named method out of it, so the symbol is known in advance.
private void OnEvent(object sender, EventArgs e)
{
// Do something
AnEvent -= OnEvent;
}
private void RegisterOnce()
{
AnEvent += OnEvent;
}
I would also recommend that you run the DoSmething code only after debugging and implement some kind of blocking mechanism if you have multitasking to prevent multiple threads from triggering the event at the same time, without having time to disconnect, and therefore everything works ...
source to share
The C # compiler will first create the lambda expression you wrote before assigning the result to the variable. So when a lambda is defined, the handler doesn't matter.
It works even though you previously assigned null to the EventHandler.
Since this closure and local variables are captured in the closure, the call handler will have the correct value during processing and it will work:
EventHandler handler=null;
handler = (s, e) =>
{
// Do something
SizeChanged -= handler;
};
SizeChanged += handler;
For all people downvoting: This will not throw a NullReferenceException. handler is a local variable that is captured in the closure, so the value of the handler inside the lambda will change when it changes in the method that contains the closure. I tested it on my PC and it works great.
source to share