public IRedisPubSubServer Start()
{
AutoRestart = true;
if (Interlocked.CompareExchange(ref status, 0, 0) == Status.Started)
{
//Start any stopped worker threads
if (OnStart != null)
OnStart();
return this;
}
if (Interlocked.CompareExchange(ref status, 0, 0) == Status.Disposed)
throw new ObjectDisposedException("RedisPubSubServer has been disposed");
//Only 1 thread allowed past
if (Interlocked.CompareExchange(ref status, Status.Starting, Status.Stopped) == Status.Stopped) //Should only be 1 thread past this point
{
try
{
Init();
SleepBackOffMultiplier(Interlocked.CompareExchange(ref noOfContinuousErrors, 0, 0));
if (OnStart != null)
OnStart();
//Don't kill us if we're the thread that's retrying to Start() after a failure.
if (bgThread != Thread.CurrentThread)
{
KillBgThreadIfExists();
bgThread = new Thread(RunLoop)
{
IsBackground = true,
Name = "RedisPubSubServer " + Interlocked.Increment(ref bgThreadCount)
};
bgThread.Start();
if (Log.IsDebugEnabled)
Log.Debug("Started Background Thread: " + bgThread.Name);
}
else
{
if (Log.IsDebugEnabled)
Log.Debug("Retrying RunLoop() on Thread: " + bgThread.Name);
RunLoop();
}
}
catch (Exception ex)
{
if (this.OnError != null)
this.OnError(ex);
}
}
return this;
}
public void Execute(string ipAddress) { Manager = new RedisManagerPool(ipAddress); StartedAt = DateTime.UtcNow; var q = new Timer { Interval = 1000 }; q.Elapsed += OnInterval; q.Enabled = true; using (PubSubServer = new RedisPubSubServer(Manager, Channel) { OnStart = () => { Console.WriteLine("OnStart: #" + Interlocked.Increment(ref StartCount)); }, OnHeartbeatSent = () => { Console.WriteLine("OnHeartbeatSent: #" + Interlocked.Increment(ref HeartbeatsSent)); }, OnHeartbeatReceived = () => { Console.WriteLine("OnHeartbeatReceived: #" + Interlocked.Increment(ref HeartbeatsReceived)); }, OnMessage = (channel, msg) => { Console.WriteLine("OnMessage: @" + channel + ": " + msg); }, OnStop = () => { Console.WriteLine("OnStop: #" + Interlocked.Increment(ref StopCount)); }, OnError = ex => { Console.WriteLine("OnError: #" + Interlocked.Increment(ref ErrorCount) + " ERROR: " + ex); }, OnFailover = server => { Console.WriteLine("OnFailover: #" + Interlocked.Increment(ref FailoverCount)); }, OnDispose = () => { Console.WriteLine("OnDispose: #" + Interlocked.Increment(ref DisposeCount)); }, OnUnSubscribe = channel => { Console.WriteLine("OnUnSubscribe: #" + Interlocked.Increment(ref UnSubscribeCount) + " channel: " + channel); }, }) { Console.WriteLine("PubSubServer StartedAt: " + StartedAt.ToLongTimeString()); PubSubServer.Start(); "Press Enter to Quit...".Print(); Console.ReadLine(); Console.WriteLine("PubSubServer EndedAt: " + DateTime.UtcNow.ToLongTimeString()); Console.WriteLine("PubSubServer TimeTaken: " + (DateTime.UtcNow - StartedAt).TotalSeconds + "s"); } }