WCF :: ServiceHost的:怪异...还活着,即使线程是死了吗?死了、线程、怪异、WCF

2023-09-04 01:11:37 作者:我的意中人是个盖世英雄

下面的新成员。很高兴看到这样一个整洁的社区。

在一些研究,我决定使用WCF在我的​​应用程序做的进程间通信的,所以我现在用的是NetNamedPipeBinding结合。

ServiceHost的托管应用程序不是一个专用的服务器,因此它必须通过一个线程来产卵ServiceHost的。到目前为止好。

所以我有类似如下:

 富()
{
    螺纹serverThread =新主题(新的ThreadStart(ServerThread));
    serverThread.Start();
    Console.WriteLine(富已退出);
}

ServerThread()
{
   乌里baseAddress =新的URI(net.pipe://本地主机/服务);
   ServiceHost的ServiceHost的=新的ServiceHost(typeof运算(为MyService),baseAddress);
   ...
   serviceHost.Open();
   Console.WriteLine(服务器线程已退出);
}
 
Java与WCF交互 一 Java客户端调用WCF服务

所以不如预期,我看到:

   - >服务器线程已退出
 - >富已退出
 

但让我惊讶的是,即使在服务器上运行的线程具有兴奋,客户端仍然可以连接到的ServiceHost和服务主机妥善处理该请求!

那么怎么来ServiceHost的仍是处理和治疗,即使它的主线程(它是在创建的)请求是死了吗?

另外有没有更好的办法让ServerThread活那么一段时间(真){主题。睡眠(100);}

感谢。

解决方案

当您拨打公开赛ServiceHost的,额外的线程将被创建侦听传入的服务请求。这样一来,你的线程可能已经运行完毕,但另一个线程已经建立,并会继续运行,直到你所说的关闭在ServiceHost的。

这可能没有必要在你的情况产卵关闭一个线程自己。只需打开应用程序的主线程你的ServiceHost。然后,您可以做你的主线程其他的东西,当你准备杀死宿主,只需拨打serviceHost.Close()。

下面是一个pretty的很好的说明,我发现:

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

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.

解决方案

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