Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7808923
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 2, 20262026-06-02T03:16:34+00:00 2026-06-02T03:16:34+00:00

I have a question how to properly add/remove event handler in multithreaded environment for

  • 0

I have a question how to properly add/remove event handler in multithreaded environment for asynchronous callbacks.

I have MyCore class which receives asynchronous callbacks from ProxyDLL which dispatches callback from unmanaged code. I have form(managed) which subscribes to events.

What would be the right approach to attaching/detaching from event. I noticed that MulticastDelegate has _invocationcount. What it does? Does inner logic of the event blocks detaching from event if callback call is in process until callback is done? Is _invocationcount exists for that puprose?
Is detathing from event (in general) is treadsafe?

class Form1
{
  EventHandler m_OnResponse;
  Int32 m_SomeValue;
  Form1()
  {
    m_OnResponse = new EventHandler(OnResponseImpl);
    m_MyCore.SetCallBackOnLogOn(m_OnResponse);
  }
  ~Form1()
  {
    m_MyCore.ReleaseCallBackOnLogOn(m_OnResponse);
  }
  private OnResponseImpl(object sender, EventArgs e)
  {
    Thread.Sleep(60*1000);

    m_SomeValue = 1;             // <<-- How to/Who guarantees that Form1 obj is still
                                 // alive. May be callback was invoked earlier and
                                 // we just slept too long

    if (!this.IsDisposed)
    {
        invokeOnFormThread(DoOnResponseImpl, sender, e);
    }
  }
}

class MyCore
{
  private event EventHandler OnLogOn;
  public void SetCallBackOnLogOn(EventHandler fn)
  {
    // lock (OnLogOn)
    {
        OnLogOn += fn;
    }
  }
  ReleaseCallBackOnLogOn(EventHandler fn)
  {
    // lock (OnLogOn)
    {
        OnLogOn -= fn;
    }
  }
  public void DoDispatchOnLogOn()
  {
    // lock (OnLogOn)
    {
      if (OnLogOn != null)
      {
        OnLogOn(this, null);
      }
    }
  }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-02T03:16:36+00:00Added an answer on June 2, 2026 at 3:16 am

    Default event add and remove operations are already thread-safe. You do not need worry about that part in most cases. It is the invocation of the multicast delegate that you need to worry about.

    public void DoDispatchOnLogOn()
    {
      EventHander local;
      lock (this)
      {
        local = OnLogOn;
      }
      if (local != null)
      {
        local(this, null);
      }
    }
    

    What I did here was to create a local variable that will hold the OnLogOn delegate chain. I am exploiting the immutability of multicast delegates here so that we can do a thread-safe check for null and the invoke sequence. The lock is only used to ensure a “fresh” read of OnLogon and it is strictly optional if you do not mind gettting a “stale” read.

    Update:

    I need to be sure that callback is not invoked when
    ReleaseCallBackOnLogOn ended unsubscribing delegate.

    For the most part the code I have will not attempt to execute any event handlers that have been unsubscribed. There is a slight a race between removing an event handler and raising the event which could cause the event handler to get executed even though it was just recently removed.

    I need to be sure that my class instance is still alive, until call to
    callback is fully done.

    Delegates hold a reference to the class instance containing the target method. This will keep your instance rooted and thus not eligible for garbage collection. You do not need to worry about this.

    I should point out that the ~Form1 finalizer is not a good a place to remove event handlers. Remember, delegates hold a reference to the instance containing the target method so in most cases that finalizer will not get called and the event handler will not be removed from the event.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have following event class. I have a question related to the Property method
I have question regarding the SQLAlchemy. How can I add into my mapped class
i asked this question yesterday but it doesnt seem to have asked properly so
I have a class called Question that has a property called Type. Based on
I have a class which inherits from BindingList to apply sorting to a bindinglist.
Thanks to this question (click me!) , I have the Source property of my
I have question about sending emails from MVC3 application. I already read for exmple
I have question about how I can save the result of function I have
I have question regarding the use of function parameters. In the past I have
I have question concerning a function I created. I would like to show the

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.