NetNamedPiping and Threading in WCF

In this article we learn about the NetNamedPiping and Threading in WCF.

Introduction

This article explains how to resolve the common threading problem of when the service and clients share the same process. When the service and clients communicate in the same process, the ideal binding used in WCF is netnamedpipe binding (the ideal term is Inter-Process Communication). 
 
Example:
 
Let's create a service that echos the received message from the client.  
 
Create a blank solution in Visual Studio and add a  separate project named service and add the following code.
  1. public class MessengerService:IMessenger  
  2.    {  
  3.        public string SendMessage(string Message)  
  4.        {  
  5.            return Message + "Received from Service";  
  6.        }  
  7.    }  
  1. [ServiceContract]  
  2.     public interface IMessenger  
  3.     {  
  4.       [OperationContract]  
  5.         String SendMessage(String Message);  
  6.     }  
Let's create a UI application where we would invoke the preceding service and also create a client that consumes the service via netNamedPipeBinding. 
 
Create a separate project named AppUI and add a WPF application. It would hold three buttons, one to start the service, the other to stop the service and the last one to send a message to the service and a label that is updated when the service echoes back the message sent from the client. The application would look as in the following:
 
 
 
Go to the App.Config and add the following code.
  1. <system.serviceModel>  
  2.   <services>  
  3.     <service name="Servce.MessengerService">  
  4.       <endpoint address="net.pipe://localhost/testservice" binding="netNamedPipeBinding" contract="Contracts.IMessenger"></endpoint>  
  5.     </service>  
  6.   </services>  
  7.   
  8.   <client>  
  9.     <endpoint address="net.pipe://localhost/testservice" binding="netNamedPipeBinding" contract="Contracts.IMessenger"></endpoint>  
  10.   </client>  
  11. </system.serviceModel>  
We have the service and client ready. All we need to do is invoke it. We will invoke it in button clicks of the application. 
  1.       private void btnstartservice_Click(object sender, RoutedEventArgs e) //Invoke the service 
  2.        {  
  3.            _host = new ServiceHost(typeof(Servce.MessengerService));  
  4.            _host.Open();  
  5.   
  6.        }  
  7.   
  8.        private void btnstopservice_Click(object sender, RoutedEventArgs e)  
  9.        {  
  10.            _host.Close();  
  11.        }  
We have the service up. Now let's send a message to the service from the client. Add the following code for the sendmessage button click.
  1. private void btnsendmsg_Click(object sender, RoutedEventArgs e)  
  2.         {  
  3.                 ChannelFactory<IMessenger> factory = new      ChannelFactory<IMessenger>("");  
  4.                 var proxy = factory.CreateChannel();  
  5.                   lbltext.Content  = proxy.SendMessage("hello");  
  6.                  factory.Close();  
  7.          }  
Run the application and click the start the service button and hit the SendMessage button, you will find that the application is not responding and will finally get an error as in the following:
 
 
This is because the service and the client are invoked from the same thread (UI Thread). It is more of a deadlock situation because the client tries to update the label that is in the UI thread, which is already locked by the service and this would eventually lead to a timeout in the client. We had figured out that the problem is because the service and client are sharing the same UI thread. Let's try to invoke the client in a separate thread.
 
Add the updated code for the sendmessage button click is:
  1. Thread t1 = new Thread(() =>  
  2.             {  
  3.                 ChannelFactory<IMessenger> factory = new ChannelFactory<IMessenger>("");  
  4.                 var proxy = factory.CreateChannel();  
  5.                   lbltext.Content  = proxy.SendMessage("hello");  
  6.                  factory.Close();  
  7.             });  
  8.             t1.IsBackground = true;  
  9.             t1.Start();  
Try to run the application and hit the SendMessage button, you would get the following error of Cross Thread Invocation. In other words, the client thread is trying to access the UI thread.
 
We can resolve the preceding error in various ways, but I will use the synchronizationcontext mechanism. Update the sendmessage buttonclick method as in the following:
  1. private void btnsendmsg_Click(object sender, RoutedEventArgs e)  
  2.         {  
  3.             Thread t1 = new Thread(() =>  
  4.             {  
  5.                 ChannelFactory<IMessenger> factory = new ChannelFactory<IMessenger>("");  
  6.                 var proxy = factory.CreateChannel();  
  7.                 var result= proxy.SendMessage("hello");  
  8.                 SetLabelContent(result);  
  9.                  factory.Close();  
  10.             });  
  11.             t1.IsBackground = true;  
  12.             t1.Start();  
  13.         }  
  14.   
  15.         private void SetLabelContent(string resut)  
  16.         {  
  17.             SendOrPostCallback _callback = new SendOrPostCallback((arg) =>  
  18.             {  
  19.                 lbltext.Content = resut;  
  20.             });  
  21.            _context.Send(_callback,null);  
  22.         }  
Now try to run the application and test it by clicking the sendmessage button. We will find that the message sent from the client is echoed by the service and it is updated by the client from the different thread.