Multi-threaded self-hosting WCF service
It lo开发者_StackOverflow中文版oks like WCF only uses one thread when using self hosting. I'd like to use several threads or a thread pool of some kind for this. Is it possible with self hosting configuration or I need to use IIS for this?
If you self host the service in UI application with default service behavior setting you will probably see the behavior you are describing. Default service behavior uses synchronization context. In case of starting the service host in the UI thread (WinForms, WPF) all requests are routed to the common windows message loop => all requests are handled sequentially by UI thread.
In any other case (including manually setting [ServiceBehavior(UseSynchronizationContext = false)]
for services hosted in the UI thread) the service host dispatches new thread from the thread pool for each request. There are some further differences based on instance context mode and concurrency mode but with default settings you will see the behavior I described.
I self-host everything- guaranteed it's not single-threaded. Commenter above is probably on the right track- make sure that if your ServiceBehavior attribute on the service impl is set to InstanceContextMode.Single that you've also set ConcurrencyMode.Multiple, otherwise you will only see one thread. The defaults if you don't have a ServiceBehavior attribute will give you one instance of the service impl per call (InstanceContextMode.PerCall, ConcurrencyMode.Single). Could also be related to connection throttling, but presumably you'd know if you set that up in your config.
[ServiceBehavior(UseSynchronizationContext = false)]
Fixed my problem. Tested this in a service and command line application after reading this comment and didn't experience the same concurrency issue. So I'll happily confirm it's only a problem when instantiated on the UI thread.
I think the lesson learnt is to use a command-line application for your WCF test harness.
精彩评论