Thread operations have never been particularly useful. I wrote some code myself: post it to share it with you.
Code
# Region simple thread, main thread and sub-thread threadAnther, local variables do not affect each other
Static void SilmpleMultThread ()
{
Thread threadAnther = new Thread (new ThreadStart (WrietConsole ));
ThreadAnther. Start (); // Start a new thread,
While (true) Console. Write ("Y"); // The main thread keeps writing "Y"
}
Static void WrietConsole ()
{
While (true) Console. Write ("X"); // keep writing "X"
}
# Endregion
# Create region copies in their respective memory stacks
Static void SimpleShareMultThread ()
{
// Copies of variable x are created in their respective memory stacks, and the output is the same;
Thread threadAnther = new Thread (new ThreadStart (Go ));
ThreadAnther. Start ();
Go ();
}
Static void Go ()
{
// Declare and use the same local variable x
For (int x = 0; x <5; x ++)
Console. Write ("*");
}
# Endregion
# Region when multiple threads reference some public target instances, they share data
Static void SimpleShareMuliThead ()
{
// Both threads call the OutPut method and share the done field. The output result is a Done.
Program prgoram = new Program ();
Prgoram. OutPut ();
Thread threadAnother = new Thread (new ThreadStart (prgoram. OutPut ));
ThreadAnother. Start ();
}
Bool done;
Public void OutPut ()
{
If (! Done) {done = true; Console. Write ("Done ");}
}
# Endregion
# Region static fields provide shared data between other threads
Static bool outDone; // static field, shared by all threads
Static object locker = new object ();
Static void simplemediastaticmulthead ()
{
Thread threadAnother = new Thread (OutDoneFunction); // another method for Thread Initialization
ThreadAnother. Start ();
OutDoneFunction ();
}
Static void OutDoneFunction ()
{
// If (! OutDone) {Console. Write ("Done"); outDone = true ;}// in this case, two "dones" are printed"
Lock (locker)
{
If (! OutDone) {Console. Write ("Done"); outDone = true ;}
} // To avoid this situation, use the lock and lock mechanism to determine that only one thread enters the critical section at the same time.
// If (! OutDone) {outDone = true; Console. Write ("Done") ;}// in this case, a "Done" is printed"
}
# Endregion