public ManualResetEvent(bool initialState) public AutoResetEvent(bool initialState)
ini tialState true, . false, .
. , ManualResetEvent . , , WaitOne () , . ,
Wait One (). , . , , Set (). Set () , . WaitOne (), . Reset () .
AutoResetEvent ManualResetEvent . ManualResetEvent , Reset (), AutoResetEvent , , , . AutoResetEvent, Reset () .
ManualResetEvent.
// , // .
Using System;
Using System.Threading;
// , , class MyThread {
Public Thread Thrd;
ManualResetEvent mre;
public MyThread(string name, ManualResetEvent evt) {
Thrd = new Thread(this.Run);
Thrd.Name = name;,
mre = evt;
Thrd.Start();
}
// , void Run() {
Console.WriteLine(" " + Thrd.Name);
for(int i=0; i<5; i++) {
Console.WriteLine(Thrd.Name);
Thread.Sleep(500);
}
Console.WriteLine(Thrd.Name + " !");
// , mre.Set();
class ManualEventDemo { static void Main() {
ManualResetEvent evtObj = new ManualResetEvent(false);
MyThread mtl = new MyThread(" 1", evtObj);
Console.WriteLine(" .");
// . evtObj.WaitOne();
Console.WriteLine(" " +
|
|
" .");
// . evtObj.Reset();
mtl = new MyThread(" 2", evtObj);
// . evtObj.WaitOne();
Console.WriteLine(" " +
" .");
}
}
, .
1
1
.
1 1 1 1 1 !
.
2 2 2 2 2 2 2 !
.
, ManualResetEvent MyThread. Run () MyThread, Set (), . Main () evtObj ManualResetEvent, , .
MyThread, evtObj. . evtObj , , MyThread Set () ^ evtObj . . , , . , , . , WaitOne () Main ().
AutoResetEvent ManualResetEvent, Reset () Main () . , , , . ManualResetEvent AutoResetEvent Reset (). , .
Interlocked
, , Interlocked. , . , Interlocked, , , . , . Interlocked , , , 64-- . .
|
|
Interlocked: Increment () Decrement (). :
public static int Increment(ref int location) public static int Decrement(ref int location)
location , .
// .
Using System;
Using System.Threading;
// , class SharedRes {
public static int Count = 0;
// SharedRes.Count , class IncThread { '
Public Thread Thrd;
public IncThread(string name) {
Thrd = new Thread(this.Run);
Thrd.Name = name;
Thrd.Start();
}
// , void Run() {
for(int i=0; i<5; i++) {