[英]C# Call method in parent thread in same class in different thread
我有个问题。 在一种形式中,我从单独的类的线程中调用了函数:
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();
}
}
在此函数中,线程“ A”中的“ mainfunction”在同一类的函数上生成一个附加线程。
现在,该子线程应该访问同一类的父线程“ A”的函数。
我知道这是如何与委托以某种形式一起访问控件的。 但在这种情况下不是。 有人可以帮我吗?
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
}
}
提前致谢。
干杯
尝试从System.Reactive使用EventLoopScheduler。 一个例子:
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);
}
}
此打印
Thread: 9
Thread: 11
Thread: 12
Thread: 11
通常,您不需要让另一个线程执行某些代码,只需要使用锁来暂停其他线程。 在这种情况下,为什么要在线程A中执行代码会很有趣。(Winforms只需要在其他线程中运行代码,因为它可以使用COM组件,而COM-Components不能很好地处理多线程)。
对于线程A,这是不可能的,因为当执行到达main方法的末尾时,它很可能已经死亡。
Windows窗体使用“分派器”概念:存在一个主循环,该循环运行直到您的程序关闭,并在通过Control.Invoke插入工作包时在其线程中执行工作包。 您也可以在mainfunction()的末尾添加一个几乎无限循环,执行Action-Delegates( https://msdn.microsoft.com/zh-cn/library/system.action ( v= vs.110).aspx )中的列表-使用ConcurrentList或在插入/删除元素时不要忘记锁定(例如,列表)。
您也可以尝试使用预定义的分派器: https : //msdn.microsoft.com/zh-cn/library/system.windows.threading.dispatcher.aspx
但也许,在这种情况下,另一种无需切换线程的解决方案可能会更好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.