This is the title of my blog when I write a single pattern of problems encountered, so today specifically wrote the demo Let yourself remember how simple to use multithreading.
What has been tangled up is how to instantiate an object multiple times in a for loop to reproduce the error of multiple instance objects in a singleton pattern without locking.
Let's first look at my multithreaded instance object, which I simply implement.
Programme one:
Demo.cs
Public classDemo {Private StaticDemo _demo =NULL; /// <summary> ///constructor Function/// </summary> PrivateDemo () {Console.WriteLine ("{0} was constructed", GetType (). Name); } /// <summary> ///gets the unique instance of the class/// </summary> /// <returns>the only instance of the class</returns> Public StaticDemo getinstance () {if(_demo = =NULL) _demo=NewDemo (); return_demo; } }
Program.cs, client code
Demo D1 =NULL; Demo D2=NULL; //Multithreading Create object Instances varT1 =NewThread (() = {D1 =demo.getinstance ();}); vart2 =NewThread (() = {D2 =demo.getinstance ();}); T1. Start (); T2. Start (); Thread.Sleep ( +);//The main thread waits for the child thread to finish executing, assigning values to the D1 and D2 variablesConsole.WriteLine ("D1 = = D2 {0}",Object. ReferenceEquals (D1, D2)); Console.read ();
Output:
Output two objects that are not the same reference, and achieve the purpose I want.
But in my mind, there is always a about for loop can be multi-threaded to create instances of the method, just can't remember, today in the data to see this method inadvertently, I immediately write down, and then add a class in the evening to write, so in the mind has an impression.
Scenario Two:
Program.cs
for (int02; i++) { new Action (() = {demo.getinstance ();}). BeginInvoke (nullnull); } Console.read ();
Output:
This debug singleton mode can reproduce the unlocked error, but also solve my heart of the question, found to solve the for loop multi-threaded creation of the method of the instance.
It's really fun!
C # Multithreading Creating object instances