Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute code on specified thread

Tags:

c#

.net

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.

like image 583
SiberianGuy Avatar asked Aug 08 '11 19:08

SiberianGuy


3 Answers

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.

like image 80
Marc Gravell Avatar answered Nov 08 '22 00:11

Marc Gravell


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.

like image 40
alun Avatar answered Nov 07 '22 23:11

alun


You should be able to use Dispatcher, at least if you are on .NET 4.

like image 3
driis Avatar answered Nov 08 '22 00:11

driis