【问题标题】:Start/stop background function启动/停止后台功能
【发布时间】:2015-10-07 19:21:47
【问题描述】:

我正在尝试开发一个 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;
}

【问题讨论】:

  • 您回答了自己的问题。在方法外(类内)设置值。
  • 您是否使用任务并行库查看任务取消?是当前取消异步工作的黄金标准msdn.microsoft.com/en-us/library/dd997396%28v=vs.110%29.aspx
  • @Polyfun 现在好点了吗?该程序是西班牙语的,所以对不起,我的英语是 4。
  • 无意冒犯,你的英语比我的西班牙语好多了;-)。
  • 但据我所知,FileSystemWatcher 不需要额外的线程。如果你想停止它,只需将 EnableRaisingEvents 设置为 false 或处置它。

标签: c# wpf


【解决方案1】:

通过在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 
  }

【讨论】:

  • 这是如何工作的?它实现了什么?这可以在事件处理程序中工作吗?
  • 必须在方法外声明,否则它仍然不会做任何事情。实际上它会在这里给出一个 NPE。