Hi All,
I have read the document in Microsoft about the exitContext in
WaitOne, but i still don't understand when to use autoEvent.WaitOne
(1000, true) or autoEvent.WaitOne(1000, false)
http://msdn.microsoft.com/en-us/library/kzy257t0.aspx
Can anyone give me more information about their different?Thanks
Use the manual reset event: ManualResetEvent. It forces you to Set
and Reset, and IMO is better than using the "automatic" you refer to.
The design context is as follows:
public static ManualResetEvent mrevent = new ManualResetEvent
(false); //used to make thread2 wait for thread1, which it depends on
below
Thread ThreadFirst, ThreadLast; //in constructor
private void AnyfunctionHere ()
{
ThreadFirst = new Thread(new ThreadStart(Function1));
if (ThreadFirst.IsAlive == false)
{
ThreadFirst.Start();
}
ThreadLast = new Thread(new ThreadStart(Function2));
if (ThreadLast.IsAlive == false)
{
ThreadLast.Start();
}
}
private void Function1()
{
//do stuff here
mrevent.Set(); //at end, unblocks other threads
}
private void Function2()
{
bool myBoolStartThisThreadYet = false;
myBoolStartThisThreadYet = mrevent.WaitOne(); //blocks this thread
until Function1 is done
if (myBoolStartThisThreadYet != true) return;
int myInt = 123;
//do stuff here that has to happen after Function1
//if you get runtime exception for certain portion of code, put that
code below inline as shown here (you can also do the same thing in
Function 1). Keep in mind there seems to be a slight performance
penalty for doing this, but it's sometimes the only way you can make
it work:
//note format!
this.Dispatcher.BeginInvoke(delegate()
{
//put runtime exception code here. You can use variables from
Function2 here (in scope)
int j = myInt; //OK
}
);
mrevent.Reset(); //sets thread2 to block mode (opposite of set).
}
RL