Search
« WPF Extensions | Main | MTG Manager – Major Update »
Tuesday
Sep222009

WCF Host and Client in Same Application

I recently found a need to host a WCF service within the same application as the client. The only real difference is the need to start the service in it’s own thread. When I originally tried hosting the service in the same thread as the client it deadlocked.

This is a simple enough matter to fix. The only gotcha, is the need to ensure the service has actually started up before making your first call from the client. I handled it with a simple flag.

   23 private ServiceHost _serviceHost;

   24 private MTGServer _server;       

   26 private bool _serverRunning;

...

 

   51 new Thread(new ParameterizedThreadStart(StartHost)).Start(hostConfiguration.Port);

   52 

   53 while (!_serverRunning)

   54 {

   55   Thread.Sleep(100);

   56 }

   57 

   58 JoinGame("localhost", hostConfiguration.Port);

...

 

   62 private void StartHost(object port)

   63 {           

   64  _server = new MTGServer();

   65 

   66  string address = String.Format("net.tcp://localhost:{0}", port);

   67 

   68  _serviceHost = new ServiceHost(_server, new Uri(address));

   69  _serviceHost.AddServiceEndpoint(typeof(Shared.IMTGServer), new NetTcpBinding(), address);

   70 

   71  _serviceHost.Open();

   73  _serverRunning = true;

 

 

In my case, I’m using a service in Singleton Context Mode. I’m not sure if this issue would exist using one of the other context modes.

PrintView Printer Friendly Version

EmailEmail Article to Friend

Reader Comments

There are no comments for this journal entry. To create a new comment, use the form below.

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>