[英]How do I ensure only one instance of the object of the class is created?
在我的A類中,我有一個ZMQ對象
public void StartLogging(object connection)
{
var ctxt = new ZMQ.Context();
var publisher = ctxt.Socket(ZMQ.SocketType.PUB);
publisher.Bind("tcp://127.0.0.1:5000");
if (connection is uint)
{
Console.WriteLine("strange");
Console.ReadLine();
}
}
B級會做類似的事情
ClassA test=new ClassA();
C級也會做同樣的事情
ClassA test=new ClassA();
這將導致創建2個ZMQ對象綁定到同一個端口,這將導致錯誤。 我該如何解決這個問題?
單身就是你需要的。 Jon Skeet的精彩文章將告訴你更多你需要知道的事情。
在你的情況下,它可能看起來像這樣:
public void StartLogging(object connection)
{
var ctxt = Singleton.Instance.Context();
var publisher = ctxt.Socket(ZMQ.SocketType.PUB);
publisher.Bind("tcp://127.0.0.1:5000");
if (connection is uint)
{
Console.WriteLine("strange");
Console.ReadLine();
}
}
public sealed class Singleton
{
private static readonly ZMQ instance = new ZMQ();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Singleton()
{
}
private Singleton()
{
}
public static Singleton Instance
{
get
{
return instance;
}
}
}
單身模式可以幫助你。
這適用於多線程應用程序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.