C # create an object instance using multiple threads,
The title of this article is a problem I encountered when writing a singleton blog. So I wrote a special demo today to let myself remember how to use multithreading easily.
The persistent struggle is how to instantiate objects multiple times in the for loop, so that the singleton mode can reproduce the error of multiple instance objects without locking.
Let's take a look at my simple multi-threaded instance objects.
Solution 1:
Demo. cs
Public class Demo {private static Demo _ demo = null; // <summary> /// constructor /// </summary> private Demo () {Console. writeLine ("{0} constructed", GetType (). name );} /// <summary> /// obtain the unique instance of this class /// </summary> /// <returns> unique instance of this class </returns> public static Demo GetInstance () {if (_ demo = null) _ demo = new Demo (); return _ demo ;}}
Program. cs, client code
Demo d1 = null; Demo d2 = null; // creates an object instance var t1 = new Thread () => {d1 = Demo. getInstance () ;}); var t2 = new Thread () =>{ d2 = Demo. getInstance () ;}); t1.Start (); t2.Start (); Thread. sleep (1000); // The main thread waits for the sub-thread to complete execution and assigns a value to the Console for the d1 and d2 variables. writeLine ("d1 = d2 {0}", object. referenceEquals (d1, d2); Console. read ();
Output:
Output two different referenced objects to achieve what I want.
However, in my mind, there has always been a method for creating instances in a for loop with multiple threads. I just couldn't remember it. I accidentally saw this method when I checked the information, I wrote it down immediately, and then added a class at night, so that I had an impression in my mind.
Solution 2:
Program. cs
for (int i = 0; i < 2; i++) { new Action(() => { Demo.GetInstance(); }).BeginInvoke(null, null); } Console.Read();
Output:
In this way, when debugging the singleton mode, we can reproduce the unlocked errors, solve my concerns, and find a solution to the multi-thread instance creation in the for loop.
So happy!