C # Implementation of Singleton design pattern (next)

Source: Internet
Author: User
Design (connected to the part)

The following is the main function, the test entrance of this program:

Using System;

Namespace Cspattern.singleton

{

public class Runmain

{

Public Runmain () {}

static public void Main (string[] args)

{

Mutilethread.mutileclient myclient = new Mutilethread.mutileclient ();

Myclient.clientmain ();

System.Console.ReadLine ();

}

}

}



The results of the implementation are as follows:

Thread Thread 1 Report: Current counter is: 2

Thread Thread 1 Report: Current counter is: 4

Thread Thread 1 Report: Current counter is: 5

Thread Thread 1 Report: Current counter is: 6

Thread Thread 3 Report: Current counter is: 7

Thread Thread 3 Report: Current counter is: 8

Thread Thread 3 Report: Current counter is: 9

Thread Thread 3 Report: Current counter is: 10

Thread Thread 0 Report: Current counter is: 1

Thread Thread 0 Report: Current counter is: 11

Thread Thread 0 Report: Current counter is: 12

Thread Thread 0 Report: Current counter is: 13

Thread Thread 2 Report: Current counter is: 3

Thread Thread 2 Report: Current counter is: 14

Thread Thread 2 Report: Current counter is: 15

Thread Thread 2 Report: Current counter is: 16



Because of the different system thread scheduling, the results of each execution are different, but the final result must be 16.

In method one, because the instance was created at the outset, the instance () method does not need to judge whether a unique instance already exists and returns the instance, so there is no problem with the counter class being instantiated multiple times.



Use Method Two:

Using System;

Using System.Threading;

Using System.Runtime.CompilerServices;

Namespace Cspattern.singleton

{

public class Counter_lazy

{

Static Counter_lazy Unicounter;

private int totnum = 0;

Private Counter_lazy ()

{

Thread.Sleep (100); Suppose multithreading is blocked for 100 milliseconds for some reason

}

[MethodImpl (methodimploptions.synchronized)]//Method's synchronization properties

Static public Counter_lazy instance ()

{

if (null = = Unicounter)

{

Unicounter = new Counter_lazy ();

}

return unicounter;

}

public void Inc () {totnum + +;}

public int Getcounter () {return totnum;}

}

}

Do not know if you have noticed the [MethodImpl (methodimploptions.synchronized)] statement above the instance () method, he is the main point of synchronization, he specified the instance () method can only be used by one thread, This avoids a thread 0 call to instance () to create a complete instance of the 1 to invoke instance () to attempt to obtain the instance.

Depending on the MSDN prompts, you can also use the Lock keyword to lock threads with the following code:

Using System;

Using System.Threading;

Namespace Cspattern.singleton

{

public class Counter_lazy

{

Static Counter_lazy Unicounter;

Static Object myObject = new Object ();

private int totnum = 0;

Private Counter_lazy ()

{

Thread.Sleep (100); Suppose multithreading is blocked for 100 milliseconds for some reason

}

Static public Counter_lazy instance ()

{

Lock (MyObject)

{

if (null = = Unicounter)

{

Unicounter = new Counter_lazy ();

}

return unicounter;

}

}

public void Inc () {totnum + +;}

public int Getcounter () {return totnum;}

}

}



Lock () is a mutex for an object that allows only one thread to access the statement block in the following curly braces until the code of the statement block is executed before it is unlocked and the other threads are unlocked before the other thread is allowed to execute its statement block.

You can also use a Mutex class to synchronize, define the private static Mutex Mut = new Mutex (), and then modify the instance () as follows to get the correct result:

Static public Counter_lazy instance ()

{

Mut. WaitOne ();

if (null = = Unicounter)

{

Unicounter = new Counter_lazy ();

}

Mut. ReleaseMutex ();

return unicounter;

}

Note that this example uses method two to change the client program for method one, remove the comment for counter_lazy.intance (), and counter.intance () comment.

Singleton mode can also be extended, as long as a little modification, you can limit in an application only allow m instances exist, and provide a global transparent access method for M instances.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.