1

I have a C# Windows application I'm working on where I kick off different classes in their own thread (ie: Class1 instance in Thread 1, Class 2 instance in Thread 2, etc).

I'm trying to correctly suspend/resume the threads, but I can't figure out how to share the lock variables for Wait/Pulse of Monitor between different classes and threads.

It seems like this should have a simple answer, I just can't figure it out. I'd really appreciate any help!

Thanks!

Yahia
  • 69,653
  • 9
  • 115
  • 144
Harry
  • 863
  • 3
  • 10
  • 26
  • 3
    `It seems like this should have a simple answer` <-- I think I see your problem. – Hogan Feb 11 '12 at 16:35
  • @L.B. without a full understanding of the problem, it is hard to comment on "static", but there is nothing in the problem/question to justify "public field" (ah, this now relates to a comment that got deleted) – Marc Gravell Feb 11 '12 at 16:45

2 Answers2

1

use public static fields, for ex.,

public class Sync
{
    public static object LockObject = new object();
    //or any other sync mechanism 
    //AutoResetEvent,ManualResetEvent,Semaphore,CountdownEvent,Mutex etc.
}
L.B
  • 114,136
  • 19
  • 178
  • 224
  • Then I could just call Sync::ManuelResetEventObj or what-not from the main class, or any threaded class? – Harry Feb 11 '12 at 17:11
  • Yes `Sync.LockObject` can be used in any thread or main class – L.B Feb 11 '12 at 17:13
  • Thanks, and I can make LockObject into an array for multiple threads being suspended simultaneously? – Harry Feb 11 '12 at 18:47
0

Monitor locking is useful for shnchronization, but when used as a messaging API it usually only scales to two threads, since you need to know exactly where each to know if it gets the message.

When things get complex, an AutoResetEvent or ManualResetEvent is usually more sensible, as they are less time critical: you get through the gate regardless of ordering.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900