dro*_*ath 13 c# multithreading
我正在寻找一种方法来重新启动已被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";
}
}
Run Code Online (Sandbox Code Playgroud)
任何的想法?
Gro*_*roo 34
一旦中止了线程,就无法重新启动它.
但是你的实际问题是你正在中止你的线程.你永远不应该使用Thread.Abort().
如果您的线程应暂停并持续多次,则应考虑使用其他机制(例如AutoResetEvent).
[编辑]
如上面的链接中Ian Griffiths所提到的,中止线程的最简单的解决方案是:
我总是推荐的方法很简单.有一个
volatile bool对工作线程和UI线程都可见的字段.如果用户单击"取消",请设置此标志.同时,在您的工作线程上,不时测试该标志.如果你看到它被设置,停止你正在做的事情.
要使其正常工作,您需要做的唯一事情是重新排列背景方法,使其在循环中运行- 这样您就可以定期检查您的标志是否已由其他线程设置.
如果你需要为同一个工作线程提供暂停和恢复功能,而不是简单的volatile bool标记方法,你可以采用稍微复杂的方法,一个同步结构,如AutoResetEvent.这些类还提供了一种方法,使工作线程在来自非工作线程的信号之间保持指定(或无限期)的时间.
该线程包含一个具有Start,Pause,Resume和Stop方法的具体示例.请注意Brannon的示例如何永远不会中止该线程.它只触发一个事件,然后等待线程正常完成.
Emi*_*elt 17
只需在doStart()中调用MyThread.Start()之前添加MyThread = new Thread(MyFunction).不要在你的方法之外创建线程,那里的空间被认为是声明.
编辑:请注意,使用thread.Abort()杀死一个线程可能非常危险.您应该尝试完成干净的多线程,就像Groo在他的帖子中描述的那样.
| 归档时间: |
|
| 查看次数: |
54217 次 |
| 最近记录: |