BackGroundWorker を何時間も動作させようとしてきました。bgw.RunWorkerAsync(); を呼び出した後に DoWork() イベントハンドラーが発生しない理由がわかりません。
関係のないコードを切り詰めたので、少し読みやすくなりました。
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);
}
}
}