Shivang MIttal
Shivang MIttal

Reputation: 1001

How to keep a console c# application running and reading input from standard input stream (not continously)

I have a console c# application (native messaging app) which is connected to a WinForms via named pipes. console app is a native messaging app connected with chrome. WinForm send the command to console app to start reading standard input stream to get messages to chrome and send it to WinForm. I dont know how to keep the console app alive so that it can wait for the events attached to get command from winform and read the standard input stream.?

This is my main function.

static void Main(string[] args)
{
         StartChannel();            
}

This is the Event handler for getting message from named Pipe

public void StartChannel()
{
    _pipeServer = new PipeServer();
    _pipeServer.PipeMessage += new DelegateMessage(PipesMessageHandler);
    _pipeServer.Listen(AppConstant.IPC_ConsoleReaderPipe);
}

private void PipesMessageHandler(string message)
{
  if(message ="Start")
       StartListener();
}

**This is my problem center. Here after executing StartListener,console application closes. How can i I keep it running in a separate thread. So that it should not block the the NamedPipe communication **

private static void StartListener()
{
        wtoken = new CancellationTokenSource();
        readInputStream = Task.Factory.StartNew(() =>
        {
            wtoken.Token.ThrowIfCancellationRequested();
            while (true)
            {
                if (wtoken.Token.IsCancellationRequested)
                {
                    wtoken.Token.ThrowIfCancellationRequested();
                }
                else
                {
                   OpenStandardStreamIn();
                }
            }
        }, wtoken.Token);
    }
}


public static void OpenStandardStreamIn()
{
    Stream stdin = Console.OpenStandardInput();
    int length = 0;
    byte[] bytes = new byte[4];
    stdin.Read(bytes, 0, 4);
    length = System.BitConverter.ToInt32(bytes, 0);
    string input = "";
    for (int i = 0; i < length; i++)
    {
        input += (char)stdin.ReadByte();
    }
    Console.Write(input);
}

Upvotes: 0

Views: 1880

Answers (1)

Matt Ko
Matt Ko

Reputation: 979

You should try using an AutoResetEvent - see http://msdn.microsoft.com/en-us/library/system.threading.autoresetevent(v=vs.110).aspx.
This way, your main thread waits on the listener thread until the event is set and only terminates after that.
If you are using .NET 4.5, you should use the async and await keywords plus Task.Run() -> see http://msdn.microsoft.com/en-us/library/hh191443.aspx

Upvotes: 1

Related Questions