Re: a few issues with events



not_a_commie wrote:
Another issue I'm having with events: it appears that you cannot
unsubscribe to an event that is currently executing. In fact, if you
have an event that, in one of its handlers, unsubscribes from another
event in the same class as the original, you're screwed. Anyone seen a
problem with this before or do I need to post an example?

You should post an example. While a problem like the one you describe should disappear if you copy the event to a local variable before executing it, I've never heard of the problem even when you don't and was unable to reproduce such a problem myself.

I think unsubscribing from an event in the handler would be a natural thing to do, so it would surprise me if this came up even in the case when you use the event directly. I coded a short test application (see below) just to be sure, and sure enough I can unsubscribe from the event I'm handling. Works fine here.

So yes, if you believe you have a problem you should post a concise-but-complete example of code that demonstrates that.

Pete



using System;

namespace TestEventUnsubscribe
{
class Program
{
static event EventHandler eventTest;

static void Main(string[] args)
{
eventTest += TestHandler;
OnTest();
OnTest();
Console.ReadLine();
}

static void OnTest()
{
if (eventTest != null)
{
eventTest(null, new EventArgs());
}
}

static void TestHandler(object sender, EventArgs e)
{
Console.WriteLine("executing TestHandler");
eventTest -= TestHandler;
}
}
}
.



Relevant Pages