gpt4 book ai didi

c# - Form.show() 从另一个线程中的事件开始

转载 作者:太空宇宙 更新时间:2023-11-03 13:20:53 26 4
gpt4 key购买 nike

我有一个类可以触发 Form 项目中的事件。触发事件的类中的方法在单独的线程中运行。问题是如何从主线程(UI 线程)加载表单

namespace test
{
public partial class Form1 : Form
{
Class1 cl1 = new Class1();
static public Form2 f2 = new Form2();
public Form1()
{
InitializeComponent();

cl1.event1 += new Class1.del(CreateForm);
}

private void button1_Click(object sender, EventArgs e)
{
cl1.Almog();
}

static public void CreateForm()
{
//Form2 f2 = new Form2();
f2.Show();
}
}
}

namespace ClassLibrary1
{
public class Class1
{
public event del event1;
public delegate void del();

public void Almog ()
{
Thread t1 = new Thread(Print);
t1.Name="class1";
t1.Start();
}
public void Print ()
{
event1();
while(true)
{
Console.WriteLine("in the loop");
}
}

}

}

最佳答案

您需要使用 MethodInvoker 调用表单。像这样……

           static public void CreateForm()
{
Form2 f2 = new Form2();
f2.Invoke(new MethodInvoker(delegate()
{

f2.Show();
}));
}

关于c# - Form.show() 从另一个线程中的事件开始,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24282703/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com