WCF Host and Client in Same Application
Tuesday, September 22, 2009 at 10:03PM 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.
.NET,
WCF in
Programming
Reader Comments