What approaches do exist to execute some code on specified thread? So let’s imagine I have a Thead and a delegate and I need to execute this delegate on this thread. How can I implement it?
I’m not interested in infrastructure things like SynchronizationContext, I want to know the ways to achieve this behavour manually.
To execute something on a specified thread, you need that thread to pull the work, for example from a synchronized queue. This could be a delegate or a known type with some kind of
Execute()method. In the case of UI frameworks, it is also usually possible to add work directly (or indirectly) to the main threads (via message queues) – for example,Control.InvokeorDispatcher.Invoke.In the case of a delegate – a standard producer/consumer queue should work fine (as long as it is thread-safe). I use one based on this answer.