Reputation: 351
Is it possible to reassign thread to a different method, once it has been instantiated. If not, are there alternatives?
Upvotes: 2
Views: 133
Reputation: 1038720
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();
Upvotes: 2
Reputation: 4186
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;
Upvotes: 1