Redis Pub/Sub ServiceStack, cancelling the thread

2019-04-28 17:16发布

问题:

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.

  1. Using the Thread.Abort. This apparently doesn't stop it, as the thread just goes into a hang then forever (no unsubscription happens).

  2. Using the _redisSubscription.UnSubscribeFromAllChannels() from the UI thread. This also causes the applicaiton to go into a blocking state forever

  3. 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?

回答1:

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.