【问题标题】:Terminate new thread with delegate when winform is closed in c# [duplicate]在c#中关闭winform时用委托终止新线程[重复]
【发布时间】:2016-10-11 04:06:25
【问题描述】:

我尝试使用 winform 应用程序创建一个新线程。这是我的示例代码。

public static bool stop = false;

private Thread mythread(){
    Thread t = new Thread(delegate() {
        while(!stop){
             // Something I want to process
        }
    });
return t;
}

private Button1_click(object sender, EventArgs e){
    stop = true; // I know it doesn't work

    this.Dispose();
    this.Close();
}

public Main(){
   InitializeComponent();

   Thread thread = mythread();
   thread.Start();
}

当 button1 被点击时,新线程和 winform 应该被终止,但新线程仍在工作。有什么办法可以终止新线程?

ps:我试图将我的代码更改为MSDN site example,但这只会让它变得更加复杂。

【问题讨论】:

  • 如果while循环中有较长的进程,退出需要时间。每隔几个命令检查一下是否停止比较好。您始终可以使用任务来实现此目标。 Tasks 有更好的取消机制。
  • 您没有正确执行此操作,线程将永远停止的可能性非零。以正确的方式做到这一点。

标签: c# .net multithreading winforms


【解决方案1】:

这是其他线程中变量的可见性问题...试试这个:

private static int stop = 0;

private Thread mythread(){
    Thread t = new Thread(delegate() {
        while(Thread.VolatileRead(ref stop) == 0){
             // Something I want to process
        }
    });
return t;
}

private Button1_click(object sender, EventArgs e){
    Thread.VolatileWrite(ref stop, 1);

    this.Dispose();
    this.Close();
}

public Main(){
   InitializeComponent();

   Thread thread = mythread();
   thread.Start();
}

注意事项:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-14
    • 1970-01-01
    • 2015-10-24
    相关资源
    最近更新 更多