简体   繁体   中英

C# Call method in parent thread in same class in different thread

I have a question. In a form I called function in a thread from a seperate class:

public partial class mainForm : Form
{
  private void button_Click(object sender, EventArgs e)
  {          
    myclass myc = new myclass();
    Thread mythread = new Thread(myc.mainfunction);
    mythread.name ="A";
    mythread.Start();
  } 
}

In this function "mainfunction" in Thread "A" is generated an additonal thread on a function of the same class.

Now this subthread should access a function of the parent thread "A" of the same class.

I know how this works with a delegate in a form to access a control. But not in this case. Could anyone help me please?

class myclass
{

    public void mainfunction ()
    {
      ...
      myclass submc = new myclass();
      Thread subthread = new Thread(new ParameterizedThreadStart(submc.subfunction));
      mythread.name ="B";
      subthread.Start(this);
    }

    public void subfunction(object parm)
    {
      myclass parentc = (myclass)parm;
      parentc.doanything()

    }

    public void doanything()
    {
     ...
     // this should happen in Thread A NOT B
    }



}

Thanks in advance.

Cheers

Try using EventLoopScheduler from System.Reactive. An example:

class Program
{
    static void Main(string[] args)
    {
        var scheduler = new EventLoopScheduler(); // will manage thread A
        WriteThreadName();
        scheduler.Schedule(WriteThreadName);
        scheduler.Schedule(() =>
        {
            // inside thread A we create thread B
            new Thread(() =>
            {
                WriteThreadName();
                scheduler.Schedule(WriteThreadName); // schedule method on thread A from thread B
            }).Start();
        });

        Console.ReadLine();

    }

    static void WriteThreadName()
    {
        Console.WriteLine("Thread: "+Thread.CurrentThread.ManagedThreadId);
    }
}

This prints

Thread: 9
Thread: 11
Thread: 12
Thread: 11

Ususally, you don't need to let another thread execute some code, you just need to pause other threads using locks. In this case, it would be interesting why you want to execute the code in thread A. (Winforms only needs to run code in other threads since it can use COM-Components, which don't handle multithreading well / at all.)

With your Thread A, this is not possible, since it probaly already died when the execution reaches the end of the main method.

Windows Forms uses a "Dispatcher" concept: There is a main loop, which runs a until your program closes, and executes work packages in its thread when they are inserted via Control.Invoke. You could add such an almost endless loop to the end of mainfunction() too, executing Action-Delegates ( https://msdn.microsoft.com/en-us/library/system.action(v=vs.110).aspx ) from a List -- use ConcurrentList or don't forget to lock (eg the list) while inserting / removing elements.

You can also try to use the predefined Dispatcher: https://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcher.aspx

But maybe, another solution without switching threads might be better in this case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM