To do this, you ll need to make use of the various synchronization objects available in C#. Some examples of the available synchronization objects are System.Threading.Mutex, System.Threading.Semaphore, System.Threading.ManualResetEvent, and System.Threading.AutoResetEvent (this is not an exhaustive list, but it s the basics). The exact synchronization object you ll want depends on your specific needs.
Mutex is probably the simplest to use, so I ll give it as an example. Say I have two functions that are running in two different threads (I ll stick with your own examples, proc1 and proc2). Both functions need to access the same variable, foo. In each function that accesses foo, you ll need to "lock" your mutex first. Then do whatever you need to do, then unlock it.
For example:
class bar
{
private int foo;
private System.Threading.Mutex lock = new System.Threading.Mutex;
public void proc1()
{
lock.WaitOne();
// do stuff to foo
lock.ReleaseMutex();
}
public void proc2()
{
lock.WaitOne();
// do stuff to foo
lock.ReleaseMutex();
}
};
Using this method, proc1 will execute. It will try to "grab" the mutex (lock). If the mutex is already grabbed, proc1 will go to sleep until the mutex is "released" by the other thread - proc1 will sit and wait, doing nothing (and eating no CPU cycles!) until the mutex is released. Then it will lock it and do its thing. No other thread will be able to grab the mutex until proc1 is done with it.
Another option is to use an Event. C# provides two types of events - manual reset and autoreset. I ll use a manual reset event for my example.
class bar
{
private System.Threading.ManualResetEvent event = new System.Threading.ManualResetEvent;
public void proc1()
{
// do stuff
event.Set();
}
public void proc2()
{
event.WaitOne();
event.Reset();
// do stuff
}
};
In this example, when proc2 is running it goes to sleep when it hits "event.WaitOne" and uses no CPU cycles until proc1 "sets" the event. Setting the event causes proc2 to wake up, and now it can do its thing. Because this is a manual reset event, the event will stay in the "set" state until event.Reset() is called.