Snickbrack
Snickbrack

Reputation: 975

Named Pipes Server exits without warning

Im trying to setup a named pipes connection between a server-software and a client.

This is my server code:

class Program
{
    private static NamedPipeServerStream server = new NamedPipeServerStream("p", PipeDirection.InOut);
    static void Main(string[] args)
    {
        Action<NamedPipeServerStream> a = callBack;
        a.BeginInvoke(server, ar => { }, null);
    }

    private static void callBack(NamedPipeServerStream pipe)
    {
        pipe.WaitForConnection();
        var line = "";
        while (line != "exit")
        {
            try
            {
                StreamReader reader = new StreamReader(pipe);
                while (line != "exit")
                {
                    line = reader.ReadLine();
                    switch (line)
                    {
                        default:
                            foo();
                            break;
                    }
                }
                break;
            }
            catch (IOException)
            {
                pipe.Disconnect();
                continue;
            }
        }
    }
}

But when I try to run this application it exits directly after the start.

I have used the debugger to reach the WaitForConnection-line and then it exits without an error or an exception. And there is nothing running but the server.

It quits without getting handled by the catch-part. Am I missing anything?

Upvotes: 1

Views: 129

Answers (1)

Joakim Hansson
Joakim Hansson

Reputation: 544

The execution is blocked on WaitForConnection and will not continue until a NamedPipeClientStream object establishes a connection to the NamedPipeServerStream object.

Please have a look here (The example should help you out): https://msdn.microsoft.com/en-us/library/system.io.pipes.namedpipeclientstream(v=vs.110).aspx

EDIT: I misunderstood the problem and originally thought that the question had to do with the execution blocking from the WaitForConnection method. The code below is the addition to the actual quesiton as well as my explanation.

The problem is the way you invoke your action. As you are calling BeginInvoke it is invoked asynchronously, on a threadpool thread. Therefor you need to check if the action has finished or not otherwise the main thread keeps running and reaches the end. I have updated my answer on how you can do this very easily

Hopefully this code helps you understand why it exists! :)

        Action<NamedPipeServerStream> a = callBack;
        var result = a.BeginInvoke(server,ar => { },null);

        while (!result.IsCompleted)
        {

        }

Upvotes: 1

Related Questions