C# 将线程重新分配给其他方法vb.net

C# 将线程重新分配给其他方法vb.net,c#,vb.net,multithreading,C#,Vb.net,Multithreading,一旦线程被实例化,是否可以将其重新分配给其他方法。如果没有,还有其他选择吗?除非线程已经启动,否则您可以使用反射,但这种方法的有用性非常值得怀疑。为什么不创建一个不同的线程实例呢 var thread = new Thread(Method1); thread .GetType() .GetMethod("SetStartHelper", BindingFlags.Instance | BindingFlags.NonPublic) .Invoke(thread, new

一旦线程被实例化,是否可以将其重新分配给其他方法。如果没有,还有其他选择吗?

除非线程已经启动,否则您可以使用反射,但这种方法的有用性非常值得怀疑。为什么不创建一个不同的线程实例呢

var thread = new Thread(Method1);
thread
    .GetType()
    .GetMethod("SetStartHelper", BindingFlags.Instance | BindingFlags.NonPublic)
    .Invoke(thread, new object[] { new ThreadStart(Method2), 0 });
thread.Start();

除非您正在调试API或托管CLR并处理内部构件,否则无法将线程“重新分配”到新方法,因为这将涉及操作线程堆栈

您可以在线程上使用命令模式向其发送可能随时间变化的工作“有效载荷”:

        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;

请注意,如果在线程启动后调用此函数,则不会产生任何效果是的,这就是为什么我使用
开始回答,除非线程已启动…