c# 请问如何在多线程任务中结束全部线程,关闭窗体?

如上。我需要在命令行下启动一个线性用来加载窗体,命令行读入用户指令操作窗体。那么当窗体被close时,如何连带主线程一起结束掉?
Application.Exit()不好用呀。
MainThread.Abort()也不行
closed事件中写入只能结束窗体不能结束主线程。哪有father?我把主线程用参数传递到窗体执行的Abort()但是没有效果。

很感谢二楼。但是我用的是命令行。跟窗体执行Dispose()方法……那个。不太一样不太一样。
主线程用来读命令,另外的一个线程启动窗体Application.Run(MainWindow);

Thread thread1 = new Thread(new ThreadStart(accp1));
thread1.IsBackground = true;
thread1.Start();

thread1.IsBackground = true;
上面的意思是把这个新线程设置成(前台或着后台...我忘了)线程,,,也就是当启动它的主进程关闭的时候它也关闭.
温馨提示:内容为网友见解,仅供参考
第1个回答  2009-05-06
最好的方法是用委托啦
在线程窗体的close事件中:
this.invoke()参数怎么填 忘了。
this是主窗体,至于怎么传给线程窗体,不难吧。
我做了个小测试 ,我这么写是可以关掉主窗体的
主窗体:
namespace test
{
public partial class Form1 : Form
{
public delegate void delegateclose();
delegateclose D;
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
D = new delegateclose(cccc);
Thread t = new Thread(new ThreadStart(threadstart));
t.Start();
}

private void threadstart()
{
delegateclose ddd = new delegateclose(this.newform);
this.Invoke(ddd);

}

private void newform()
{
Form2 f = new Form2(this, D);
f.Show();
}

public void cccc()
{
this.Dispose();
}
}
}
线程窗体:
namespace test
{
public partial class Form2 : Form
{
Form1 F;
Form1.delegateclose D;
public Form2(Form1 f,Form1.delegateclose d)
{
InitializeComponent();
F = f;
D = d;
}

private void Form2_FormClosed(object sender, FormClosedEventArgs e)
{
F.Invoke(D);
}
}
}
第2个回答  2009-05-06
在closed事件里写。
顺便把father也结束掉。
第3个回答  2020-01-04
最好的方法是用委托啦
在线程窗体的close事件中:
this.invoke()参数怎么填
忘了。
this是主窗体,至于怎么传给线程窗体,不难吧。
我做了个小测试
,我这么写是可以关掉主窗体的
主窗体:
namespace
test
{
public
partial
class
Form1
:
Form
{
public
delegate
void
delegateclose();
delegateclose
D;
public
Form1()
{
InitializeComponent();
}
private
void
button1_Click(object
sender,
EventArgs
e)
{
D
=
new
delegateclose(cccc);
Thread
t
=
new
Thread(new
ThreadStart(threadstart));
t.Start();
}
private
void
threadstart()
{
delegateclose
ddd
=
new
delegateclose(this.newform);
this.Invoke(ddd);
}
private
void
newform()
{
Form2
f
=
new
Form2(this,
D);
f.Show();
}
public
void
cccc()
{
this.Dispose();
}
}
}
线程窗体:
namespace
test
{
public
partial
class
Form2
:
Form
{
Form1
F;
Form1.delegateclose
D;
public
Form2(Form1
f,Form1.delegateclose
d)
{
InitializeComponent();
F
=
f;
D
=
d;
}
private
void
Form2_FormClosed(object
sender,
FormClosedEventArgs
e)
{
F.Invoke(D);
}
}
}
第4个回答  2019-08-09
可以用线程的
join方法
等待线程结束。
相似回答