WCF:: ServiceHost: Oddity…Still alive even if thread is dead?

こ雲淡風輕ζ 提交于 2019-12-20 02:26:26

问题


a new member here. Nice to see such a neat community.

After a bit of research, I decided to use WCF in my application to do inter process communication, so I am using the NetNamedPipeBinding binding.

The ServiceHost hosting application is not a dedicated server, so it has to spawn the ServiceHost via a thread. So far so good.

So I have something like the following:

Foo()
{
    Thread serverThread = new Thread(new ThreadStart(ServerThread));
    serverThread.Start();
    Console.WriteLine("Foo Exited");
}

ServerThread()
{
   Uri baseAddress = new Uri("net.pipe://localhost/service");
   ServiceHost serviceHost = new ServiceHost(typeof(MyService), baseAddress);
   ...
   serviceHost.Open();
   Console.WriteLine("Server Thread Exited");
}

So as expected, I see:

->   Server Thread Exited
->   Foo Exited

But to my surprise, even though the thread the server is running on has excited, the client can still connect to the serviceHost and the service host processes the request properly!

So how come the ServiceHost is still processing and treating requests even though it's main thread (the one it was created on) is dead?

Also is there a better way to keep the ServerThread alive then a while(true){Thread. Sleep(100);}?

Thanks.


回答1:


When you call Open on the ServiceHost, an additional thread will be created to listen for incoming service requests. In this way, your thread may have finished running, but another thread has been created, and will continue to run until you call "Close" on the ServiceHost.

It may not be necessary in your case to spawn off a thread yourself. Just Open your ServiceHost in the application's main thread. You can then do other things in your main thread, and when you're ready to kill the host, just call serviceHost.Close().

Here's a pretty good description I found:

http://www.code-magazine.com/article.aspx?quickid=0701041&page=1



来源:https://stackoverflow.com/questions/932690/wcf-servicehost-oddity-still-alive-even-if-thread-is-dead

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!