启动/停止后台功能

本文关键字:后台 功能 启动 | 更新日期: 2023-09-27 18:16:20

我正在尝试开发一个WPF应用程序,该应用程序在按下按钮时在后台运行其他进程(并在再次按下相同按钮时停止它)。

这里的关键是我调用的进程它将监视一个文件夹,所以,它不会在任何点结束。

我尝试过线程,但是当我按下按钮创建一个新的线程对象时,当我再次按下它时,我无法访问它,因为有不同的代码块。

我认为更好的方法是使用BackgroundWorker,但是我不知道如何使用它。

这是我现在拥有的代码。mon是创建的具有我想在后台运行的功能的对象(mon.MonitoriceDirectory)

if (this.monitoring)
{
    var dialog = new System.Windows.Forms.FolderBrowserDialog();
    dialog.ShowNewFolderButton = false;
    System.Windows.Forms.DialogResult result = dialog.ShowDialog();
    if (dialog.SelectedPath != "")
    {
         monitorizeButton.Content = "Stop";
         textBlockMonitorize.Text = "Monitoring...";
         this.monitorizando = false;
         mon.monitorizePath = dialog.SelectedPath;
         Thread newThread = new Thread(mon.MonitorizeDirectory);
         newThread.Start();
    }
}
else
{
    newThread.Abort(); // Here is the problem, I can't access to that cuz
                      // it's in another codeblock.
    monitorizeButton.Content = "Monitorice";
    textBlockMonitorize.Text = "Ready";
    this.monitorizando = true;
}

启动/停止后台功能

通过在if块外声明newThread,可以帮助您将其范围扩展到else部分;所以你可以试试这个

  Thread newThread;
  if (this.monitorizing)
  {
    var dialog = new System.Windows.Forms.FolderBrowserDialog();
    //rest of code here 
    newThread = new Thread(mon.MonitorizeDirectory);
    //Rest of code
  }
 else
  {
    newThread.Abort();
    //Rest of code here 
  }