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

  • SEARCH
  • Home
  • 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 8305745
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 8, 20262026-06-08T18:11:09+00:00 2026-06-08T18:11:09+00:00

In the following code I have two classes, one that runs in a separate

  • 0

In the following code I have two classes, one that runs in a separate thread and fires events, the other that subscribes to this event and receives data from the event. The event code I have based off of Jon Skeet’s article http://csharpindepth.com/Articles/Chapter2/Events.aspx

In this article http://www.codeproject.com/Articles/37474/Threadsafe-Events it says…

For this reason, I recommend the same approach that Jon Skeet ends up recommending at the end of Delegates and Events: “don’t do that”, i.e., don’t use events in a multithreaded fashion. If an event exists on an object, then only one thread should be able to subscribe to or unsubscribe from that event, and it’s the same thread that will raise the event.

Now obviously my design breaks that, in that it fires the event on a different thread to that it was subscribed on. How could I modify my design so that it adhears to the principle of not using events in a multi-threaded fashion or is this not possible ?

The other way I thought of doing it was just to pass in my callback method as a delegate into class B and call that instead of calling the event?

I may have completely the wrong end of the stick, so any clarification would be appreciated.

Note: I am aware that .Net 4.0 has apparently solved this issue, however I would still be interested in if there is a way to do it pre .Net 4

public delegate void MyDelegate(int a);

class A
{
    void main()
    {
        B bObject = new B();
        bObject.MyEvent += new MyDelegate(NiceMethod);
        bObject.Run();
    }   

    void NiceMethod(int a)
    {   
        Console.Writeline({0}, a);  
    }
}

class B
{
    readonly object eventLock = new object();

    MyDelegate myDel;

    public event MyDelegate MyEvent
    {   
        add
        {
            lock (eventLock)
            {
                myDel += value;
            }
        }
        remove
        {
            lock (eventLock)
            {
                myDel -= value;
            }
        }
    }   

    //Assume this runs in a new thread and calls back data using MyEvent
    //Have ommited thread code for simplicity
    public void Run()
    {
        for (int i = 0; i < 100; i++)
        {
            Thread.Sleep(1000);
            MyDelegate handler;
            lock (someEventLock)
            {
                handler = myDel;
            }
            if (handler != null)
            {
                handler (i);
            }
        }   
    }
}
  • 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-08T18:11:10+00:00Added an answer on June 8, 2026 at 6:11 pm

    There isn’t anything wrong about raising events or listening to events from different threads. It is the responsibility of the listener to deal with being invoked from another thread. As Marc Gravell notes in his comment, adding and removing of listeners to and from events from different threads is (and always has been) supported by the compiler generated add and remove implementations. The only problem is to raise the event in a thread safe fashion, which can be done by synchronizing the access to event via the same kind of spinlock the generated add and remove are using:

    class B 
    {  
        public event MyDelegate MyEvent;
    
        protected OnMyEvent(int p_Arg)
        {
            // Delegates are immutable and add/remove default
            // implementations always generate a new instance of the 
            // delegate. Therefore, tTmp (if not null) can be safely invoked
            var tTmp = 
                System.Threading.Interlocked
                .CompareExchange(ref MyEvent, null, null);
            if (tTmp != null) {
                tTmp(p_Arg);
            }
        }
    
        //Assume this runs in a new thread and calls back data using MyEvent 
        //Have ommited thread code for simplicity 
        public void Run() 
        { 
            for (int i = 0; i < 100; i++) 
            { 
                OnMyEvent(i);
            }    
        } 
    } 
    

    The only thing that could happen is that the listener is invoked after it has been removed from the event list. IMHO, the listener must be able to deal with this situation as it deals with beeing invoked from separate threads…

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

Sidebar

Related Questions

I have the following code (in this case for two images - but in
I have the following problem. I have two classes, in this case A and
I have two following rows of code: Microsoft.VisualBasic.Interaction.Beep() or Microsoft.VisualBasic.Beep() The result is the
I have two identical byte arrays in the following segment of code: /// <summary>
I have the following two code blocks. Code block 1 var checkboxes = $(div.c1
Imagine you have two views with code like the following: controller_a/a.html.erb <%= content_tag(:div) do
I have the following code to generate two random numbers var attackRoll = Math.floor((Math.random()*6)+1);
I have the following code to validate two text box entries to make sure
I have the following code which will generate two pdf files containing plots to
I have the following code which lets the user plot two points on a

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.