Skip to main content
 首页 » 编程设计

c#之从主 UI 线程上的按钮挂起子线程

2024年02月23日17zengkefu

我找到了这个主题,How to suspend a thread by its name from the main thread? ,但对于我要实现的目标没有令人满意的答案。

我正在使用线程和 WatiN 类同时在同一窗口窗体中的两个浏览器上执行事件。

我想从主 UI 线程中按下其中一个浏览器中可用的暂停按钮,通过派生按下暂停按钮的浏览器的控件名称,使用该名称找出哪个子-线程与其运行逻辑相关联,并暂停该运行逻辑,直到按下播放按钮。

如今,我们在代码和技术方面已经如此成熟,应该有办法做到这一点。

你怎么看?

研究思路:

实用地创建 ManualResetEvent 并为其命名,使用 UI 暂停按钮获取打开的浏览器控件名称,该名称以子线程和浏览器控件名称(例如 browser_5 和 thread_5)类似地命名,以某种方式定位在 MRE 中子线程,并关闭门以暂停逻辑。 (但这可以在主 UI 线程的子线程上完成吗?)

请您参考如下方法:

不要使用thread.Suspend

乍一看,您似乎可以 use thread.Suspend() to pause it和 thread.Resume() to unpause it .但这不是一个好主意。参见 the MSDN article for thread.Suspend for why you should never use it除非您打算终止该线程的 AppDomain。

Do not use the Suspend and Resume methods to synchronize the activities of threads. You have no way of knowing what code a thread is executing when you suspend it. If you suspend a thread while it holds locks during a security permission evaluation, other threads in the AppDomain might be blocked. If you suspend a thread while it is executing a class constructor, other threads in the AppDomain that attempt to use that class are blocked. Deadlocks can occur very easily.

子循环可以,但并不完美

这不是最佳选择,但您可以使用与 the one described in that question you linked 类似的技术.

不是在按下停止按钮时退出循环,而是让它在暂停时进入并在子循环内等待。在该子循环中执行 Thread.Sleep 以防止 CPU Hook 。

这可能不是最高效的代码,因为它保持线程运行,并在恢复时再挂起 100 毫秒。

public class YourForm : Form 
{ 
  private volatile bool _pause = false; 
 
  private void StartButton_Click(object sender, EventArgs e) 
  { 
    var thread = new Thread( 
      () => 
      { 
        while (...) 
        { 
          // Periodically poll the _pause flag. 
          while (_pause) 
          { 
            // Now that we're paused, wait until we're unpaused 
            // before proceeding further in the outer loop 
            Thread.Sleep(100); 
          } 
 
          // Todo: The rest of the processing here 
        } 
      }); 
    thread.Start(); 
  } 
 
  private void PauseButton_Click(object sender, EventArgs e) 
  { 
    _pause = !_pause; // Toggle 
  } 
} 

使用线程同步

最好的选择是使用各种线程同步结构之一,like ManualResetEvent .暂停线程正是它们的设计目的。它们非常高效,因为它们是 implemented with a mutex .

public class YourForm : Form 
{ 
  private volatile bool _pause = false; 
  private static ManualResetEvent mre = new ManualResetEvent(true); 
 
  private void StartButton_Click(object sender, EventArgs e) 
  { 
    var thread = new Thread(ThreadImplementation); 
    thread.Start(); 
  } 
 
  private void PauseButton_Click(object sender, EventArgs e) 
  { 
    _pause = !_pause; 
 
    if(_pause) 
    { 
      mre.Reset(); 
    } 
    else 
    { 
      mre.Set(); 
    } 
  } 
 
  private void ThreadImplementation() 
  { 
    while (...) 
    { 
      // Periodically wait on the event 
      mre.WaitOne(); 
 
      // Todo: The rest of the processing here 
    } 
  } 
}