我正在使用消耗WCF Web服务的多线程c#应用程序。与web服务的连接将会有一个特定的超时时间,我们可以定义它,然后关闭。我正在寻找使用单例类存储连接到Web服务。我想获得实例如下:多线程c#应用程序中的懒惰单例
CLazySingleton ins = CLazySingleton.Instance;
string connection = CLazySingleton.abc;
下面是单身类的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LazySingleton
{
public class CLazySingleton
{
private static readonly Lazy<CLazySingleton> _instance
= new Lazy<CLazySingleton>(() => new CLazySingleton());
private static readonly object ThreadLock = new object();
public static string abc;
//I will use the service connection object in place of 'abc' in the application
//assume that 'abc' is storing the connection object
private CLazySingleton()
{ }
public static CLazySingleton Instance
{
get
{
if (abc == null)
{
lock (ThreadLock)
{
//Make the connection
abc = "Connection stored in this variable";
Console.WriteLine("Connection Made successfully");
return _instance.Value;
}
}
else
{
return _instance.Value;
}
}
}
}
}
我的问题是:1。 这是否代码能够照顾多的线程试图同时获取实例?这是我目前最关心的问题。 2.我可以有更好的解决方案吗? 3.我是否需要在此处使用“锁定”或使用Lazy方法来处理尝试获取实例的多线程?
任何帮助,将不胜感激。
谢谢!
看看这篇文章由乔恩斯基特。它在讨论Singleton模式方面做得很好。 http://www.yoda.arachsys.com/csharp/singleton.html – juharr 2013-03-05 11:29:14
我对你的方法有些怀疑。为什么你需要维护一个单身人士的连接?如果每个线程都有自己的代理/连接,是否有问题?而且由于它是一项网络服务,如果您创建了许多连接,我不会预见到任何问题。 ---更好地理解你的“连接”是什么样的对象? – thewpfguy 2013-03-08 06:24:45
你不需要锁 – Rafa 2014-02-14 15:55:24