I have a console application which uses an external library. The library insists on always being called from the same thread; it locks up otherwise. (I did try runn
Since ExecuteInWorkerThread
runs all actions on one thread, it will block if called recursively. So I suspect your hang maybe because you have an action calling the library, which then calls the library again via ExecuteInWorkerThread
before completing.
I've not tested your ThreadManager class; my gut says it looks too complicated though, so as an aside, if you don't mind including Reactive Extensions (nuget package rx-main), then you can refactor your ThreadManager class like this:
public class ThreadManager
{
EventLoopScheduler _scheduler = new EventLoopScheduler();
public T ExecuteInWorkerThread<T>(Func<T> action)
{
return Observable.Start(action, _scheduler).Wait();
}
}
And you can add this method to it if you need an async call too:
public Task<T> ExecuteInWorkerThreadAsync<T>(Func<T> action)
{
return Observable.Start(action, _scheduler).ToTask();
}
You need to understand SynchronizationContext
concept, especially in the context of the WCF. I strongly recommend to read an excellent Programming WCF Services book, where it is described in details. But generally speaking, you can create your own custom SynchronizationContext
that creates thread affinity for service calls. There is an example of it in the above mentioned book, but you can read about it also from the same author on MSDN, section Thread Affinity Synchronization Context, which is an example of exactly what you need.
On further examination, it seems that I forget to wrap some of the external library calls, causing the library to deadlock the server. Now that I've fixed that, everything works perfectly...
Sorry for being dumb.