简体   繁体   English

不同线程中同一类的父线程中的C#调用方法

[英]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. 在此函数中,线程“ A”中的“ mainfunction”在同一类的函数上生成一个附加线程。

Now this subthread should access a function of the parent thread "A" of the same class. 现在,该子线程应该访问同一类的父线程“ A”的函数。

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. 尝试从System.Reactive使用EventLoopScheduler。 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.) 在这种情况下,为什么要在线程A中执行代码会很有趣。(Winforms只需要在其他线程中运行代码,因为它可以使用COM组件,而COM-Components不能很好地处理多线程)。

With your Thread A, this is not possible, since it probaly already died when the execution reaches the end of the main method. 对于线程A,这是不可能的,因为当执行到达main方法的末尾时,它很可能已经死亡。

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. Windows窗体使用“分派器”概念:存在一个主循环,该循环运行直到您的程序关闭,并在通过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. 您也可以在mainfunction()的末尾添加一个几乎无限循环,执行Action-Delegates( https://msdn.microsoft.com/zh-cn/library/system.action ( v= vs.110).aspx )中的列表-使用ConcurrentList或在插入/删除元素时不要忘记锁定(例如,列表)。

You can also try to use the predefined Dispatcher: https://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcher.aspx 您也可以尝试使用预定义的分派器: https : //msdn.microsoft.com/zh-cn/library/system.windows.threading.dispatcher.aspx

But maybe, another solution without switching threads might be better in this case. 但也许,在这种情况下,另一种无需切换线程的解决方案可能会更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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