Chris W
Chris W

Reputation: 145

Event Callbacks with Threading in C#

I have a class B (implementation of INotifyPropertyChanged) that monitors for events. It sits inside a class A that receives the event notifications. The events class B generates can often be very frequent, so I'd like to:

  1. Run the code for class A on a thread ThA (not interacting with containing class, B)

  2. Run the code for class B on a thread ThB, and when an event occurs, before notifying the containing class A of the event (by doing an invoke on the dispatcher for ThA?), it checks that ThA is not in use by class A. This way, I would keep it so that only ThA runs inside A, and also avoid overwhelming ThA with notifications from class B (info from class B will create events for class A "only when ThA has time").

So it might look something like this -

public class A
{
     private B b
     private Thread ThA

     public A
     {
         b= new B(ThA);
         b.PropertyChanged+=..
     }

     Event1 callback running on ThA
     Event2 callback running on ThA
     Callback for b (invoked in ThA)
}

public class B : INotifyPropertyChanged
{
       private Thread ThA
       private Thread ThB

       public B(ThA_)
       {
            ThA=ThA_;
       }

       private void EventInClassB_Updated(object sender, Args e)
       {
            if (ThA is not being used for anything)
            {
                DispatcherForThreadA.invoke( notifyPropertyChanged() ); //send the callback to class A
            }
       }

}

Does anyone know if there is a smarter way to do this, and if not, how I might encode "ThA is not being used for anything"?

Thanks! Chris

Upvotes: 2

Views: 1288

Answers (1)

Jim Mischel
Jim Mischel

Reputation: 133995

You could use a Monitor or a Mutex to control access to ThA. Simply call Monitor.TryEnter to get the lock. If TryEnter fails, then ThA is in use. Be sure to call Monitor.Exit when ThA is done.

The code for using a Mutex would be similar. In general, the Monitor will perform better, but it can't be used across app domain boundaries.

Upvotes: 2

Related Questions