views:

252

answers:

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?

+1  A: 

See this thread for a great approach.

Basically, just store your inlined method in a delegate, and unsubscribe it during your finally.

Reed Copsey
+2  A: 

You could try something like this:

public static void DoSomething()
{
    bool cancel = false;
    EventHandler<EventArgs> handler = delegate { cancel = true; };

    try
    {
     MyStaticClass.MyEvent += handler;
    }
    finally
    {
     MyStaticClass.MyEvent -= handler;
    }
}
Andrew Hare
Cheers, it seems so obvious now I see it :)
johnc