This maybe a more general threading question i'm not sure.
But I've got a WPF app that subscribes to channels and listens for messages from a redis database.
App.SubscriptionThread = new Thread(() =>
{
_redisSubscription.SubscribeToChannels("ChannelA", "ChannelB");
});
App.SubscriptionThread.Start();
Once I start this I have no idea how to stop it.
Things I've tried.
Using the Thread.Abort
. This apparently doesn't stop it, as the thread just goes into a hang then forever (no unsubscription happens).
Using the _redisSubscription.UnSubscribeFromAllChannels()
from the UI thread. This also causes the applicaiton to go into a blocking state forever
Forcefully shutdown using Environment.Exit(0)
. This one seems to do the trick. Unfortunetly it also has the side effect of...well...shutting down my application.
How do I go about just stopping the listening, so I can connect/reconnect at will?
Am I doing it wrong by starting the SubscribeToChannels in a new thread?
However a small handful of Redis commands are long-term blocking or non-atomic. The PUBSUB subscribe and psubscribe commands are non-atomic in that the command will register it's request to have any messages sent to the given channel(s) sent to it as well, but the actual data can arrive much later – ie.
Aside from data storage, Redis can be used as a Publisher/Subscriber platform. In this pattern, publishers can issue messages to any number of subscribers on a channel. These messages are fire-and-forget, in that if a message is published and no subscribers exists, the message evaporates and cannot be recovered.
More precisely, Redis Pub/Sub is designed for real-time communication between instances where low latency is of the utmost importance, and as such doesn't feature any form of persistence or acknowledgment.
Redis Pub/Sub implements the messaging system where the senders (in redis terminology called publishers) sends the messages while the receivers (subscribers) receive them. The link by which the messages are transferred is called channel. In Redis, a client can subscribe any number of channels.
An example that shows how to subscribe and unsubscribe from messages is in RedisMqServer, e.g:
using (var subscription = redisClient.CreateSubscription())
{
subscription.OnUnSubscribe = channel =>
Log.Debug("OnUnSubscribe: " + channel);
subscription.OnMessage = (channel, msg) =>
{
if (msg == "STOP")
{
Log.Debug("Stop Command Issued");
Log.Debug("Unsubscribing from all Channels...");
subscription.UnSubscribeFromAllChannels(); //Unblocks thread.
}
};
subscription.SubscribeToChannels(QueueNames.TopicIn); //blocks thread
}
Where it uses a custom control message to unblock the background thread and unsubscribe from all channels from the subscription OnMessage handler.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With