重新启动在.NET线程(使用C#) [英] Restarting a thread in .NET (using C#)
本文介绍了重新启动在.NET线程(使用C#)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找一种方式来重新启动已停止以中止()线程..
I'm looking for a way to restart a thread that has been stopped by Abort()..
public partial class MyProgram : Form
{
private Thread MyThread = new Thread(MyFunction);
private System.Windows.Forms.Button startStopBtn = new System.Windows.Forms.Button();
public MyProgram()
{
MyThread.Start();
startStopBtn += new EventHandler(doStop);
startStopBtn.Text = "Stop";
}
private static void MyFunction()
{
// do something
}
private void doStop(object sender, EventArgs e)
{
MyThread.Abort();
startStopBtn -= new EventHandler(doStop);
startStopBtn += new EventHandler(doStart);
startStopBtn.Text = "Start";
}
private void doStart(object sender, EventArgs e)
{
MyThread.Start(); // << Error returned when clicking the button for 2nd time
startStopBtn -= new EventHandler(doStart);
startStopBtn += new EventHandler(doStop);
startStopBtn.Text = "Stop";
}
}
任何想法?
Any idea?
推荐答案
简单的调用MyThread.Start()在DOSTART()之前添加MyThread的=新主题(MyFunction的)。不要创建你的方法外螺纹,空间有思想的声明。
Simply add MyThread = new Thread(MyFunction) before calling MyThread.Start() in doStart(). Do not create the thread outside of your methods, the space there is thought for declarations.
编辑:请注意,杀人与Thread.Abort的)一个线程(可能是非常危险的。你应该尽量做到干净多线程,就像Groo在他的文章中描述。
这篇关于重新启动在.NET线程(使用C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文