我正在开发一个多线程的C#应用程序,它正在消费一个WCF Web服务。与Web服务的连接将有一个特定的超时时间,我们可以定义超时时间,在此之后连接将关闭。我希望使用单例模式来存储Web服务的连接。我正尝试按以下方式获取实例:
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. 我需要在这里使用“lock”还是使用“Lazy”方法就可以处理多线程尝试获取实例?
任何帮助都将不胜感激。
谢谢!