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.Invoke
or Dispatcher.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.
If you just mean that you want to use the same thread for more than one action you could use a thread pulling from a blocking collection. Short demo:
class Program
{
static void Main(string[] args)
{
var c = new System.Collections.Concurrent.BlockingCollection<Tuple<bool, Action>>();
var t = new Thread(() =>
{
while (true)
{
var item = c.Take();
if (!item.Item1) break;
item.Item2();
}
Console.WriteLine("Exiting thread");
});
t.Start();
Console.WriteLine("Press any key to queue first action");
Console.ReadKey();
c.Add(Tuple.Create<bool, Action>(true, () => Console.WriteLine("Executing first action")));
Console.WriteLine("Press any key to queue second action");
Console.ReadKey();
c.Add(Tuple.Create<bool, Action>(true, () => Console.WriteLine("Executing second action")));
Console.WriteLine("Press any key to stop the thread");
Console.ReadKey();
c.Add(Tuple.Create<bool, Action>(false, null));
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
}
The thread will just block on Take until you queue an action up and then execute it and wait for the next one.
You should be able to use Dispatcher
, at least if you are on .NET 4.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With