Autoresetevent is also a synchronization object, which is used for exclusive access to resources.
When autoresetevent is in the terminated State, if there is a waiting thread, the autoresetevent variable will automatically change to the non-terminated state after the thread is executed.
CodeExample:
Code
Class Program
{
Static Void Main ( String [] ARGs)
{
Caclultae calc = New Caclultae ();
Console. writeline ( " Result = {0} " , Calc. Result ( 234 ). Tostring ());
Console. Read ();
}
}
Class Caclultae
{
Double Basenum, firnum, secnum, thdnum;
Autoresetevent [] autoevents;
Manualresetevent manualevent;
Random generator;
Public Caclultae ()
{
Autoevents = New Autoresetevent []
{
New Autoresetevent ( False ),
New Autoresetevent ( False ),
New Autoresetevent ( False )
};
Manualevent = New Manualresetevent ( False );
}
Void Calbase ( Object Stateinfo)
{
Basenum = Generator. nextdouble ();
Console. writeline ( " Basenum is OK " );
Manualevent. Set ();
}
Void Calfirst ( Object Stateinfo)
{
Double Precalc = Generator. nextdouble ();
Manualevent. waitone ();
Console. writeline ( " Firstnum begins to calculate " );
Firnum = Precalc * Basenum * Generator. nextdouble ();
Autoevents [ 0 ]. Set ();
Console. writeline ( " Firstnum calculates successfully " );
}
Void Calsec ( Object Stateinfo)
{
Double Precalc = Generator. nextdouble ();
Manualevent. waitone ();
Console. writeline ( " Secnum begins to calculate " );
Secnum = Precalc * Basenum * Generator. nextdouble ();
Autoevents [ 1 ]. Set ();
Console. writeline ( " Secnum calculates successfully " );
}
Void Calthird ( Object Stateinfo)
{
Double Precalc = Generator. nextdouble ();
Manualevent. waitone ();
Console. writeline ( " Thrdnum begins to calculate " );
Thdnum = Precalc * Basenum * Generator. nextdouble ();
Autoevents [ 2 ]. Set ();
Console. writeline ( " Thrdnum calculates successfully " );
}
Public Double Result ( Int Seed)
{
Generator = New Random (SEED );
Threadpool. queueuserworkitem ( New Waitcallback (calbase ));
Threadpool. queueuserworkitem ( New Waitcallback (calfirst ));
Threadpool. queueuserworkitem ( New Waitcallback (calsec ));
Threadpool. queueuserworkitem ( New Waitcallback (calthird ));
Waithandle. waitall (autoevents );
Manualevent. Reset ();
Return Firnum + Secnum + Thdnum;
}
}
In the code, we focus on the autoresetevent synchronization object. From the code, we can see that the calfirst, calsec, and calthird methods all contain autoevents []. set () Code. This Code is the thread that notifies you to wait for this signal. I have completed my task and you can get this signal, in other words, you are more sure to execute your own tasks.
In the result method, we can see waithanle. watiall () Code. This code indicates the result method. It waits until all the signal Variables change to the terminated state, so that he can execute his own code.
Execution result:
As you can see, the result is executed only after the other three methods are executed.