views:

32

answers:

2

Is it possible to reassign thread to a different method, once it has been instantiated. If not, are there alternatives?

+1  A: 

Unless the thread has started you could use reflection but the usefulness of such thing is very doubtful. Why not create a different thread instance instead:

var thread = new Thread(Method1);
thread
    .GetType()
    .GetMethod("SetStartHelper", BindingFlags.Instance | BindingFlags.NonPublic)
    .Invoke(thread, new object[] { new ThreadStart(Method2), 0 });
thread.Start();
Darin Dimitrov
Note that if this is called after the thread is started, this does not have any effect
Florian Doyon
Yes, that's why I started my answer with `Unless the thread has started ...`.
Darin Dimitrov
A: 

Unless you are doing some weird things with the debugging API or hosting the CLR and playing with the internals, there's no way a thread can be 'reassigned' to a new method as that would involve manipulating the stack of the thread.

What you can do is use a command pattern on your thread to send it work 'payloads' that might change in time:

        Action worker=null;
        bool running = true;
        var t = new Thread(() =>
                            {
                                while(running)
                                {
                                    Action theWorker = worker;
                                    if(theWorker!=null)
                                    {
                                        theWorker();    
                                    }
                                    Thread.Sleep(10);
                                }
                            });
        worker = new Action(() => Console.WriteLine("hi mum"));

        t.Start();
        Thread.Sleep(100);
        worker=new Action(()=>Console.WriteLine("I can see my house from here"));
        Thread.Sleep(100);
        running = false;
Florian Doyon