Reputation: 331
In my class A, I have a ZMQ object
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();
}
}
Class B will do something like
ClassA test=new ClassA();
Class C will also do something the same
ClassA test=new ClassA();
This will result in 2 ZMQ object being created binding to the same port which will result in error. How do I fix this problem?
Upvotes: 3
Views: 3233
Reputation: 553
Welcome to
singleton pattern
here is what MSDN has: http://msdn.microsoft.com/en-us/library/ff650316.aspx
Upvotes: 0
Reputation: 15865
A singleton is what you need. Jon Skeet's excellent article will tell you more than you need to know.
In your case it might look something like this:
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;
}
}
}
Upvotes: 6