且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Windows窗体运行WCF

更新时间:2023-12-06 17:19:10

我原来的答复是关闭的。一些研究后,这里的真正原因是和引用:

这是因为你开始你的WCF ServiceHost的UI线程。

由于任何人谁在Windows中做多线程UI编程知道,你不能没有同步回使用类似Control.Invoke方法UI线程更新UI。

在默认情况下WCF的ServiceHost处理从线程池自己的线程的所有请求。但是,当您启动WCF的ServiceHost的UI线程上,WCF检测到UI线程与相关联的的SynchronizationContext。 WCF检测这一点,而不是使用线程池来处理请求,将调度到UI线程所有传入的请求。这样做的原因是,这意味着WCF服务器组件code可以安全地更新界面。

所以,即使你的WCF服务可能不会做的UI都WCF任何互动将利用这一机制,由于正在启动在UI线程上。

简单的解决方法是应用ServiceBehavior属性与UseSynchronizationContext设置为false。或启动ServiceHost的另一个线程(如你发现)。

下面是一些更多的细节: http://bytes.com/topic/net/answers/750778-wcf-inproc-client-server-main-thread-client-call-hangs
http://www.softinsight.com/bnoyes/PermaLink.aspx?guid=4bea53fa-2553-4d7b-bfe2-b0f0e9d11d0a

抱歉原来的误区。希望这有助于。

I've a program working as client and server. I'm using wcf services with BasicHttpBinding and the program is running in a console application.

When i moved the code to a windows forms application, everything stops working. When the client side invoke one operation, it doesn't returns. When some operation on server side is invoked, it causes a time out on the caller.

I resolved the problem moving the client and server code to a dedicated thread.
It seems that the thread responsible for processing the window events (the form owner) could not be the same that instances the ServiceHost object.
Can anyone tell me why?

Thanks

PS: I'm using .Net 3.5 and Windows Vista

My original answer was off. After some research here is the real reason and references:

It is because you started your WCF ServiceHost on the UI thread.

As anyone who has done multi-threaded UI programming in Windows knows, you can't update the UI without synchronizing back to the UI thread using something like the Control.Invoke method.

By default WCF ServiceHost handles all requests on their own threads from the threadpool. However, when you start the WCF ServiceHost on the UI thread, WCF detects that the UI thread has a SynchronizationContext associated with. WCF detects this and instead of using the threadpool to handle request it dispatches all incoming requests to the UI thread. The reasoning behind this is that this means the WCF Server component code can update the interface safely.

So even though your WCF service may not do any interaction with the UI at all WCF will use this mechanism due to being started on the UI thread.

Simple fix is to apply the ServiceBehavior attribute with UseSynchronizationContext set to false. Or start the ServiceHost on another thread (as you discovered).

Here are some more details: http://bytes.com/topic/net/answers/750778-wcf-inproc-client-server-main-thread-client-call-hangs
http://www.softinsight.com/bnoyes/PermaLink.aspx?guid=4bea53fa-2553-4d7b-bfe2-b0f0e9d11d0a

Sorry for the original misleadings. Hope this helps.