我一直试图让 BackGroundWorker 工作几个小时。我似乎无法找出为什么我的 DoWork() 事件处理程序在调用 bgw.RunWorkerAsync(); 后没有得到提升;
我已经减少了不相关的代码,所以它更容易阅读。
namespace FolderMonitor
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using FolderMonitor.Properties;
public partial class MainForm : Form
{
private ExistingFileHandler exist = new ExistingFileHandler();
private MonitoredFileHandler handler = new MonitoredFileHandler();
private Monitor monitor;
private BackgroundWorker bgw = new BackgroundWorker();
public MainForm(Monitor monitor)
{
this.monitor = monitor;
InitializeComponent();
InitializeBackgroundWorker();
txtFolderPath.Text = Settings.Default.monitoredFolder;
txtNewFolderPath.Text = Settings.Default.destinationFolder;
btnStop.Enabled = false;
}
private void InitializeBackgroundWorker()
{
bgw.DoWork += new DoWorkEventHandler(bgw_DoWork);
bgw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgw_RunWorkerCompleted);
bgw.ProgressChanged += new ProgressChangedEventHandler(bgw_ProgressChanged);
}
private void BtnStart_Click(object sender, EventArgs e)
{
btnStop.Enabled = true;
btnStart.Enabled = false;
exist.HandleExistingFiles(txtFolderPath.Text);
listBoxFiles.Items.Clear();
MonitoredFileHandler.MonitoredFolderPath = txtFolderPath.Text;
MonitoredFileHandler.DestinationFolderPath = txtNewFolderPath.Text;
this.bgw.RunWorkerAsync();
}
private void BtnStop_Click(object sender, EventArgs e)
{
this.bgw.CancelAsync();
btnStart.Enabled = true;
btnStop.Enabled = false;
}
private void bgw_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
if (!worker.IsBusy)
{
monitor.StartFolderMonitor(txtFolderPath.Text);
}
}
private void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
btnStart.Enabled = true;
btnStop.Enabled = false;
}
private void bgw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
handler.MonitoredFiles.Add(txtNewFolderPath.Text);
}
}
}