Arvo Bowen
Arvo Bowen

Reputation: 4955

Cannot access a disposed object when raising a threaded event

My class I'm writing is using multi threads and I have this extension method I have created for my class to raise events in a thread safe way.

static class MultiThreadHelper
{
    public static object Raise(this MulticastDelegate eventToRaise, object sender, EventArgs e)
    {
        object retVal = null;

        MulticastDelegate threadSafeMulticastDelegate = eventToRaise;
        if (threadSafeMulticastDelegate != null)
        {
            foreach (Delegate d in threadSafeMulticastDelegate.GetInvocationList())
            {
                var synchronizeInvoke = d.Target as ISynchronizeInvoke;
                if ((synchronizeInvoke != null) && synchronizeInvoke.InvokeRequired)
                {
                    retVal = synchronizeInvoke.EndInvoke(synchronizeInvoke.BeginInvoke(d, new[] { sender, e }));
                }
                else
                {
                    retVal = d.DynamicInvoke(new[] { sender, e });
                }
            }
        }

        //Return the value of the event invocation or null if none.
        return retVal;
    }
}

When my form tries to close a lingering thread is still trying to report back and it raises an event that no longer has a handler.

I end up getting the following error...

enter image description here

What kind of check can I run before that line error occurs? Is there anything else I can do or different approach I can take to resolve the issue?

Upvotes: 0

Views: 286

Answers (1)

Scott Baldwin
Scott Baldwin

Reputation: 431

My first thought would be that ManifestBuilder is not unsubscribing from the delegate when it is being closed. Make sure you unsubscribe using the -= syntax.

Upvotes: 2

Related Questions