开发者

running WCF in windows forms

开发者 https://www.devze.com 2023-01-21 00:00 出处:网络
I\'ve a program worki开发者_运维百科ng as client and server. I\'m using wcf services with BasicHttpBinding and the program is running in a console application.

I've a program worki开发者_运维百科ng 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号