IPC using named Pipes fails to connect on second run

77 views Asked by At

I want to achieve inter process communication between the UI and background process. From the UI thread ,I want to start an operation in a background process. The background process then will send back the progress of the operation to the UI process.

I am trying to use named-pipes to achieve this.

I have defined my client and sever as shown below

CancellationTokenSource m_TokenSource
// This will start a namedpipe server
public void StartServer()
{ 
    m_TokenSource = new CancellationTokenSource();
    CancellationToken token = m_TokenSource.Token;
    Task.Factory.StartNew(() =>
    {
        m_ProgressCollection.CollectionChanged += M_ProgressCollection_CollectionChanged;
        var server = new NamedPipeServerStream("Action");
        server.WaitForConnection();
        var reader = new StreamReader(server);
        while (!token.IsCancellationRequested)
        {
            var line = reader.ReadLine();
            if (line != null)
                m_ProgressCollection.Add(line); //adding data to a observable collection
        }       
        server.Disconnect();
       
    }, token);

}   

//client
public void StartClient()
{
    pipeClient = new NamedPipeClientStream("Action");                
    pipeClient.Connect(5000);
    writer = new StreamWriter(pipeClient);
    writer.WriteLine("10");
    Thread.Sleep(1000); //simulating some operation
    writer.WriteLine("50");
    Thread.Sleep(1000); //simulating some operation
    writer.WriteLine("100");
}
    

I am using using these client and server as shown below

From UI thread I am calling PerformOperation() function This will start the server and a new background process

public void PerformOperation()
{
   StartServer();
   StartbackgroundProcess();
}

In the background process, I'm calling the client to send some data to server

public void StartbackgroundProcess()
{
   //do some operation and send progress
   StartClient();
}

Once the background operation is done , I'm requesting the task which runs the server to be cancelled using the m_TokenSource token.

Lets say clicking on a UI button will call PerformOperation(). When I click on the button for the first time, everything works fine. When I click on the button again, the client fails to connect.( fails at pipeClient.Connect(5000) )

Please let me know if i have missed anything.

0

There are 0 answers