T. Wiener
T. Wiener

Reputation: 41

How to keep StackExchange.Redis open while subscribed

My program closes even when subscribed to a channel. Is there a correct way to keep this open? (ex no Console.ReadLine();)

using System;
using StackExchange.Redis;

namespace redis.test
{
    class Program
    {
        static void Main(string[] args)
        {
            ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost");
            IDatabase db = redis.GetDatabase();

            ISubscriber sub = redis.GetSubscriber();

            sub.Subscribe("test", (channel, message) => {
                Console.WriteLine("Got notification: " + (string)message);
            });
        }
    }
}

Upvotes: 1

Views: 788

Answers (2)

littlecodefarmer758
littlecodefarmer758

Reputation: 976

Use ManualResetEvent.

using (var exitEvent = new ManualResetEvent(false))
{
    Console.CancelKeyPress += (sender, eventArgs) =>
    {
        eventArgs.Cancel = true;
        exitEvent.Set();
    };

    ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost");
    IDatabase db = redis.GetDatabase();
    ISubscriber sub = redis.GetSubscriber();
    sub.Subscribe("test", (channel, message) => {
        Console.WriteLine("Got notification: " + (string)message);
    });

    Console.WriteLine("waiting...");
    exitEvent.WaitOne();
}

Upvotes: 2

MDuh
MDuh

Reputation: 425

answering from reddit:

Seeing this code, the current behavior of what you are describing is intended since the program is already done after that console.writeline().

I'm not exactly sure what you want to do to not kill the application after the writeline. If you could say the reason why you want to suspend the application after the writeline then maybe I can help you more.

If you just want to see the output afterwards, you could pipe the output to a text file by doing

cmd /c "C:\path\to\your\application.exe" > myfile.txt

but, console.readline() is an easier way to do that

Upvotes: 0

Related Questions