【发布时间】:2016-03-10 04:55:16
【问题描述】:
我正在尝试实现 BackgroundWorker 来监控 FileSystemWatcher 服务。
我的代码分为:
Classes.cs 包含所有方法、变量和FileSystemWatcher 实现。和主要的 Form1 ,其中包含表单数据和对按钮\等的调用。当我运行我的程序时,所发生的只是改变光标(这是已经预料到的) - 动作发生在后台(事情已经完成),但我的进度条上没有显示任何报告。我从一个网站上得到了这个例子,并把它改编成我的代码——我做错了什么吗?我相信这与我唯一调用的是文件系统观察器这一事实有关——但我希望它会根据“在后台”运行的操作报告进度。
感谢任何帮助。谢谢
我的 form1 代码(BackgroundWorker 部分)和FileSystemWatcher 如下:
namespace PPF_Converter_v10
{
public partial class Form1 : Form
{
private FileManipulation prg;
//private FileManipulation FileOp;
public Form1()
{
InitializeComponent();
//FileOp = new FileManipulation();
prg = new FileManipulation();
//Load config before the program begins - loading sample config or newly generated config
prg.LoadConfig();
FillTextBox();
bgWorker.DoWork += new DoWorkEventHandler(bgWorker_DoWork);
}
BackgroundWorker 代码:
private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
if (!textBox1.Text.Contains("\\"))
{
MessageBox.Show("Please define the input folder before starting");
}
else if (!textBox2.Text.Contains("\\"))
{
MessageBox.Show("Please define the XML Output folder before starting");
}
else if (!textBox3.Text.Contains("\\"))
{
MessageBox.Show("Please define the Converted PPF Output Folder before starting");
}
else if (!textBox4.Text.Contains("\\"))
{
MessageBox.Show("Please define the Invalid PPF Output Folder before starting");
}
else
{
// calls the watcher
// prg.FileWatcher.SynchronizingObject = progressBar1.
prg.ProgramProcessing(textBox1.Text);
}
// do some long-winded process here
// this is executed in a separate thread
int maxOps = 1000000;
for (int i = 0; i < maxOps; i++)
{
//rtbText.AppendText(i.ToString() + "\r\n");
// report progress as a percentage complete
bgWorker.WorkerReportsProgress = true;
bgWorker.ReportProgress(100 * i / maxOps);
}
}
private void bgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// update the progress bar
pbProgress.Value = e.ProgressPercentage;
}
private void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// return to "normal" mode of operation
this.Cursor = Cursors.Default;
btnGo.Enabled = true;
}
private void btnGo_Click_1(object sender, EventArgs e)
{
// give the appearance of something happening
this.Cursor = Cursors.WaitCursor;
btnGo.Enabled = false;
// call RunWorkerAsync to start the background thread
bgWorker.RunWorkerAsync();
}
启用RichtextBox 时抛出异常:
附加信息:跨线程操作无效:控件“rtbText”从创建它的线程以外的线程访问。
【问题讨论】:
标签: c# multithreading backgroundworker filesystemwatcher