WCF threading - non-responsive UI

旧街凉风 提交于 2019-11-30 13:36:13

问题


I'm trying to configure some WCF stuff. Currently, I have a server which allows remote users to download files, and client. In the server, I use a ServiceHost class. I assume it should be running on a separate thread, however, the server UI (WinForms) becomes locked when someone downloads a file. Is there a way to manage the WCF threading model?

Thank you!


回答1:


You should add a ServiceBehaviorAtttribute to the class implementing your service and set its UseSynchronizationContext property to false. This will cause calls to your service to be processed on their own thread.

Example:

[ServiceBehavior(UseSynchronizationContext=false)]
class YourService : IYourService
{
  // Service Methods
}

Just remember that if you are going to update any Controls from within your service methods, you must bear in mind the cross-thread programming model of Windows Forms.




回答2:


"From the same Windows Form application if you were to construct the ServiceHost instance before starting the UI thread, it will run on its own thread. That means worker threads allocated from the thread pool process messages instead of the message loop. Thus, services can truly process multiple concurrent requests. "




回答3:


You shouldn't host a WCF Service inside a UI program. WCF has a very specific threading model, that will prevent your UI from running nicely.

Basically, the WCF threading scheme changes depending on the instance management behavior selected, and also when there are no requests reaching the service during a time period WCF might suspend the running thread. All of this will cause trouble with the UI.

What I do in this situations, is to create a Windows Service hosting WCF, and create a ServiceContract to expose the needed data to the monitoring UI. This UI will run independtly in it's own exe, being another client of the service, fetching the data from the service as needed.

I hope makes sense for you.



来源:https://stackoverflow.com/questions/2949477/wcf-threading-non-responsive-ui

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