Invoke question when dealing with multiple threads

C

Chuck

I am creating a pub/sub broker implementation in C# and I am having some
trouble understanding how I should best implement the invoke portion in
order to make sure it is as thread-safe as it can be.

The "broker" class allows other objects to subscribe to messages that will
get published by other objects. To subscribe they pass in a Object that
represents thier instance (aka 'this') and a String that contains the method
name to be invoked. When a particular message is published the instance and
method name are used to forward the message (and any data that was sent with
it) to the subscriber so they can process it. Each message may have zero or
more subscribers as well.

To process the queued messages I am using a System.Timers.Timer class which
uses a separate thread to handle the delay between the timer events. Inside
the Timer elapsed event I am forwarding all of the queued messages to any
subscribers that are interrested in them.

To perform the Invoke I am doing the following which I believe will cause
problems.

Instance.GetType().GetMethod(MethodName).Invoke(Instance, Parms);

Where Instance is an Object that the subscriber passed in (aka 'this'),
MethodName is a String that contains a public method to be invoked, and
Parms is a Object[] that contains the parameters that the method is
expecting.

How thread-safe is this since there are at least 2 threads being used
(whatever the application thread is and the Timer thread.) I will not know
ahead of time what the subscriber actually is - plain class, WinForms class,
etc.

I have seen mention of ISynchronizeInvoke, Invoke, BeginInvoke and EndInvoke
but I am not sure exactly how they play into this sort of environment.

Any suggestions or input would be appreciated.

Chuck
 
H

Howard Swope

If you have no other threads acting in your system, you could use the
System.Windows.Forms.Timer which will have your timer routine called by the
thread processing your message pump. In your scenario it doesn't look like
timing is too critical. This way you stay single threaded. If you have other
worker threads in your system already than you have to worry about
synchronization anyway and you might as well get the performance advantage
of System.Threading.Timer.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top