2015-10-07 100 views
0

我试图开发一个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; 
} 
+3

你回答了你自己的问题。在方法之外设置值(在类中)。 – kevintjuh93

+0

您是否看过任务并行库的任务取消?这是取消异步工作的当前黄金标准https://msdn.microsoft.com/en-us/library/dd997396%28v=vs.110%29.aspx – Gusdor

+0

@Polyfun现在好点?该程序是西班牙语,所以请原谅我的英语。 –

回答

0

通过声明newThread出侧if块帮助你扩大余地的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 
    } 
+0

这是如何工作的?它实现了什么?这会在事件处理程序中工作吗? – Gusdor

+1

必须在方法外部声明,否则它将不会执行任何操作。实际上它会在这里提供NPE。 – kevintjuh93

+0

看来是有用的,谢谢! –