I am writing a library that consumes a resource, and for some reason the API was designed in such a way that events will occur in different threads, but API calls must be made in the main thread.
Let's say the API I'm trying to use is defined as (I will omit event definitions):
public sealed class DodgyService { public void MethodThatHasToBeCalledOnTheMainThread() { ... } }
To use this API, I added a service to my library called Service (Yup, a very original name) that will create a new task (which will work in the main thread, as I specify the TaskScheduler that was created from SynchronizationContext ).
Here is my implementation:
public class Service { private readonly TaskFactory _taskFactory; private readonly TaskScheduler _mainThreadScheduler; public Service(TaskFactory taskFactory, TaskScheduler mainThreadScheduler) { _taskFactory = taskFactory; _mainThreadScheduler = mainThreadScheduler; }
}
Now, if I make a call to my service (in the main thread) and try to wait for the main thread, the application comes to a standstill, as the main thread will wait for the scheduled tasks to be completed on the main thread.
How to redirect these calls to the main thread without blocking the whole process?
At some point, I thought about doing a main thread discovery before creating a new task, but I don't want to hack this.
For everyone who is interested, I got a gist here with code and a WPF application that shows the problem.
In btw, the library should be written in .net framework 4.0
Change! I solved my problem following the advice of Scott Chamberlain as provided here
rodrigoelp
source share