- Jon Skeet - < sk *** @ pobox.com> http://www.pobox.com/~skeet 如果回复该群组,请不要给我发邮件。 /> FYI./// <summary>/// Author: William Stacey/// Fast and simple way to implement a singleton pattern without resorting/// to nested classes or other static vodo. Can also be easily converted to/// allow "n" number of instances to be created./// </summary>public class SingletonClass{// Vars used by singleton logic.private static int created = 0; // No object created yet.private static SingletonClass singletonInstance = null;// End singleton vars. // Other private/public vars as needed in class.private string name; public SingletonClass(){name = "MyName";Console.WriteLine("Created MyName.");//other stuff...} /// <summary>/// Returns single instance of SingletonClass if it exists. Otherwise/// create it, store the reference and return the singleton./// This uses very fast Interlocked method that does its work via CPU/// instructions in an atomic way. Almost as fast as an "if" test, while/// being thread safe and not requiring kernel mode switch or otherlocking./// </summary>/// <returns>The singleton object.</returns>public static SingletonClass GetInstance(){if ( Interlocked.Exchange(ref created, 1) == 1 )return singletonInstance;singletonInstance = new SingletonClass();return singletonInstance;} /// <summary>/// Reset "created" to zero. Next call to GetInstance() will create/// a new SingletonClass obj. Can be used as to "refresh" and create/// a new object daily or per some other event. This method is threadsafe./// </summary>public static void ResetSingleton(){Interlocked.Exchange(ref created, 0);} public string Name{get { return this.name; }}} --William Stacey, MVP 解决方案 That''s not threadsafe. There are two main problems: 1) Threads could end up with a return value of null if they callGetInstance just after another call to GetInstance which has set the"created" flag but not actually created the instance yet. 2) Threads could end up with a reference to the singleton before it hasfinished being constructed - the reference assignment could berearranged to before the content of the actual constructor. You don''thave any memory barriers, so there''s no guaranteed ordering of thereads and writes. --Jon Skeet - <sk***@pobox.com> http://www.pobox.com/~skeetIf replying to the group, please do not mail me too Nope, you''ve then got the same problem as the normal double-check lockalgorithm - you could see the reference to the singleton before it''sproperly initialised. You basically need a memory barrier there *somewhere*. --Jon Skeet - <sk***@pobox.com> http://www.pobox.com/~skeetIf replying to the group, please do not mail me too 这篇关于简单快速的单身模式为你。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-27 13:45