Synchronization means that in a multi-threaded program, in order to allocate critical resources between two or more threads, how can we allocate critical resources so that other threads cannot use them when they are used by a thread, which can effectively avoid deadlocks and dirty data. Dirty data refers to the use of a certain data by two threads at the same time, resulting in an unpredictable state of this data! In C #, there are several ways to process thread synchronization: Wait for an event: when an event occurs, another event occurs.
[Csharp]
<Pre class = "html" name = "code"> using System;
Using System. Collections. Generic;
Using System. Text;
Using System. Threading;
Namespace ConsoleApplication1
{
Public class ClassCounter
{
Protected int m_iCounter = 0;
Public void Increment ()
{
M_iCounter ++;
}
Public int Counter
{
Get
{
Return m_iCounter;
}
}
}
Public class EventClass
{
Protected ClassCounter m_protectedResource = new ClassCounter ();
Protected ManualResetEvent m_manualResetEvent = new ManualResetEvent (false); // ManualResetEvent (initialState). If initialState is true, the initial state is set to terminate. If it is false, set the initial status to non-terminating.
Protected void ThreadOneMethod ()
{
M_manualResetEvent.WaitOne (); // here, the thread whose entry is ThreadOneMethod is set to wait
M_protectedResource.Increment ();
Int iValue = m_protectedResource.Counter;
System. Console. WriteLine ("{Thread one}-Current value of counter:" + iValue. ToString ());
}
Protected void ThreadTwoMethod ()
{
Int iValue = m_protectedResource.Counter;
Console. WriteLine ("{Thread two}-current value of counter;" + iValue. ToString ());
M_manualResetEvent.Set (); // activate the waiting thread
}
Static void Main ()
{
EventClass exampleClass = new EventClass ();
Thread threadOne = new Thread (new ThreadStart (exampleClass. ThreadOneMethod ));
Thread threadTwo = new Thread (new ThreadStart (exampleClass. ThreadTwoMethod ));
ThreadOne. Start (); // note that thread 1 is executed first.
ThreadTwo. Start (); // run thread 2 again. The value of thread 2 should be larger than thread 1, but the result is the opposite.
Console. ReadLine ();
}
}
}
ManualResetEvent allows threads to send messages to each other.
The result is as follows:
{Thread two}-current value of counter; 0
{Thread one}-Current value of counter: 1
Author: szstephen Zhou