C# RunWorkerAsync()之后后台工作进程将不会启动
C#新手-我从网上找到的一个示例项目中拼凑了一些代码,这些代码与我试图完成的内容非常接近-但它拒绝以同样的方式运行。到目前为止,我已经学到了很多,做了很多调整,但这篇文章继续逃避我,我在网上找不到任何完全相同的东西。在示例程序中,backgroundWorker.RunWorkerAsync();直接跳到程序的下一部分。在我的代码中,它不会。我在许多不同的地方放置了中断,它总是在RunWorkerAsync()处停止并挂起。我认为部分问题在于,示例程序的原始作者使用后台工作人员的方式与我在网上看到的大多数示例不一致……但当我自己运行示例程序时,它在示例程序中工作。我错过了什么C# RunWorkerAsync()之后后台工作进程将不会启动,c#,backgroundworker,C#,Backgroundworker,C#新手-我从网上找到的一个示例项目中拼凑了一些代码,这些代码与我试图完成的内容非常接近-但它拒绝以同样的方式运行。到目前为止,我已经学到了很多,做了很多调整,但这篇文章继续逃避我,我在网上找不到任何完全相同的东西。在示例程序中,backgroundWorker.RunWorkerAsync();直接跳到程序的下一部分。在我的代码中,它不会。我在许多不同的地方放置了中断,它总是在RunWorkerAsync()处停止并挂起。我认为部分问题在于,示例程序的原始作者使用后台工作人员的方式与我在网上看
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Text.RegularExpressions;
namespace DIPUtil
{
public partial class DIPform : Form
{
#region Fields
private string outputDirectory;
protected string findWhatString = "BEGIN";
protected string replaceWithText = "FANOODLE";
#endregion
#region Background
BackgroundWorker worker = new BackgroundWorker();
/// <summary>
/// Executes the main find and replace operation.
/// </summary>
/// <param name="worker">The BackgroundWorker object.</param>
/// <returns>The number of files affected by the replace operation.</returns>
private int DoFindReplace(BackgroundWorker worker)
{
//Initialize the affected count variable
int filesAffectedCount = 0;
//Initialize the counter
int counter = 0;
//Get all XML files in the directory
string[] filesInDirectory = Directory.GetFiles(outputDirectory, "*.txt");
//Initialize total file count
int totalFiles = filesInDirectory.GetLength(0);
//Analyze each file in the directory
foreach (string file in filesInDirectory)
{
//Perform find and replace operation
if (FindAndReplace(file))
{
//The file was changed so increment variable
filesAffectedCount++;
}
//Increment the counter
counter++;
//Report progress
worker.ReportProgress((int)((counter / totalFiles) * 100.00));
}
//Return the total number of files changed
return filesAffectedCount;
}
#endregion
#region FindAndReplace
/// <summary>
/// Performs the find and replace operation on a file.
/// </summary>
/// <param name="file">The path of the file to operate on.</param>
/// <returns>A value indicating if the file has changed.</returns>
private bool FindAndReplace(string file)
{
//holds the content of the file
string content = string.Empty;
//Create a new object to read a file
using (StreamReader sr = new StreamReader(file))
{
//Read the file into the string variable.
content = sr.ReadToEnd();
}
//Get search text
string searchText = GetSearchText(findWhatString);
//Look for a match
if (Regex.IsMatch(content, searchText))
{
//Replace the text
string newText = Regex.Replace(content, searchText, replaceWithText);
//Create a new object to write a file
using (StreamWriter sw = new StreamWriter(file))
{
//Write the updated file
sw.Write(newText);
}
//A match was found and replaced
return true;
}
//No match found and replaced
return false;
}
#endregion
#region Various
/// <summary>
/// Gets the text to find based on the selected options.
/// </summary>
/// <param name="textToFind">The text to find in the file.</param>
/// <returns>The text to search for.</returns>
private string GetSearchText(string textToFind)
{
//Copy the text to find into the search text variable
//Make the text regex safe
string searchText = Regex.Escape(findWhatString);
return searchText;
}
/// <summary>
/// Sets the properties of the controls prior to beginning the download.
/// </summary>
private void InitializeProcess()
{
//Get sources
outputDirectory = txtDirectory.Text;
//Set properties for controls affected when replacing
statuslabel.Text = "Working...";
progbar.Value = 0;
progbar.Visible = true;
btnprocess.Enabled = false;
btncancel.Enabled = true;
//Begin downloading files in background
backgroundWorker.RunWorkerAsync();
}
/// <summary>
/// Sets the properties of the controls after the download has completed.
/// </summary>
private void DeinitializeProcess()
{
//Set properties for controls affected when operating
statuslabel.Text = "Ready";
progbar.Visible = false;
btnprocess.Enabled = true;
btncancel.Enabled = false;
}
/// <summary>
/// Displays the directory browser dialog.
/// </summary>
private void BrowseDirectory()
{
//Create a new folder browser object
FolderBrowserDialog browser = new FolderBrowserDialog();
//Show the dialog
if (browser.ShowDialog(this) == DialogResult.OK)
{
//Set the selected path
txtDirectory.Text = browser.SelectedPath;
}
}
/// <summary>
/// Validates that the user input is complete.
/// </summary>
/// <returns>A value indicating if the user input is complete.</returns>
private bool InputIsValid()
{
//Set the error flag to false
bool isError = false;
//Clear all errors
errorProvider.Clear();
//Validate the directory name
if (string.IsNullOrEmpty(txtDirectory.Text))
{
errorProvider.SetError(txtDirectory, "This is a required field.");
isError = true;
}
else
{
//check to make sure the directory is valid
if (Directory.Exists(txtDirectory.Text) == false)
{
errorProvider.SetError(txtDirectory, "The selected directory does not exist.");
isError = true;
}
}
//Return a value indicating if the input is valid
if (isError)
return false;
else
return true;
}
#endregion
#region Events
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
//Create a work object and initialize
BackgroundWorker worker = sender as BackgroundWorker;
//Run the find and replace operation and store total files affected in the result property
e.Result = (int)DoFindReplace(worker);
}
private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
//Update the prog bar
progbar.Value = e.ProgressPercentage;
}
private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//The background operation is done
DeinitializeProcess();
//Perform final operations
if (e.Error != null)
MessageBox.Show(this, e.Error.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
else if (e.Cancelled)
MessageBox.Show(this, "The operation was ended by the user.", "Cancelled.", MessageBoxButtons.OK, MessageBoxIcon.Error);
else
MessageBox.Show(this, string.Format("{0} files were updated by the operation.", e.Result.ToString()), "Replace Complete", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
public DIPform()
{
InitializeComponent();
}
private void DIPform_Load(object sender, EventArgs e)
{
}
private void btnprocess_Click(object sender, EventArgs e)
{
//Verify input is ok
if (InputIsValid())
InitializeProcess();
}
private void btncancel_Click(object sender, EventArgs e)
{
}
//private void linkbrowse_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
// {
//Select a directory to output files
// BrowseDirectory();
//}
private void linkbrowse_LinkClicked_1(object sender, LinkLabelLinkClickedEventArgs e)
{
//Select a directory to output files
BrowseDirectory();
}
#endregion
}
}
使用系统;
使用System.Collections.Generic;
使用系统组件模型;
使用系统数据;
使用系统图;
使用系统文本;
使用System.Windows.Forms;
使用System.IO;
使用System.Text.RegularExpressions;
名称空间DIPUtil
{
公共部分类双窗体:窗体
{
#区域字段
私有字符串输出目录;
受保护的字符串findWhatString=“BEGIN”;
受保护的字符串replaceWithText=“FANOODLE”;
#端区
#区域背景
BackgroundWorker工人=新的BackgroundWorker();
///
///执行主查找和替换操作。
///
///BackgroundWorker对象。
///受替换操作影响的文件数。
私人int DoFindReplace(后台工作人员)
{
//初始化受影响的计数变量
int fileaffectedcount=0;
//初始化计数器
int计数器=0;
//获取目录中的所有XML文件
字符串[]filesInDirectory=Directory.GetFiles(outputDirectory,*.txt);
//初始化文件总数
int totalFiles=filesInDirectory.GetLength(0);
//分析目录中的每个文件
foreach(filesInDirectory中的字符串文件)
{
//执行查找和替换操作
如果(查找并替换(文件))
{
//该文件已更改为增量变量
fileaffectedcount++;
}
//递增计数器
计数器++;
//报告进展
worker.ReportProgress((int)((计数器/总文件)*100.00));
}
//返回更改的文件总数
返回fileaffectedcount;
}
#端区
#区域查找和替换
///
///对文件执行查找和替换操作。
///
///要操作的文件的路径。
///指示文件是否已更改的值。
私有布尔FindAndReplace(字符串文件)
{
//保存文件的内容
string content=string.Empty;
//创建新对象以读取文件
使用(StreamReader sr=新StreamReader(文件))
{
//将文件读入字符串变量。
content=sr.ReadToEnd();
}
//获取搜索文本
string searchText=GetSearchText(findWhatString);
//找一根火柴
if(Regex.IsMatch(content,searchText))
{
//替换文本
字符串newText=Regex.Replace(内容、搜索文本、替换为文本);
//创建新对象以写入文件
使用(StreamWriter sw=新StreamWriter(文件))
{
//写入更新的文件
sw.Write(新文本);
}
//找到匹配项并替换
返回true;
}
//未找到匹配项并进行替换
返回false;
}
#端区
#地区不同
///
///获取要基于选定选项查找的文本。
///
///要在文件中查找的文本。
///要搜索的文本。
私有字符串GetSearchText(字符串textToFind)
{
//将要查找的文本复制到搜索文本变量中
//使文本regex安全
string searchText=Regex.Escape(findWhatString);
返回搜索文本;
}
///
///在开始下载之前设置控件的属性。
///
private void InitializeProcess()
{
//获取来源
outputDirectory=txtDirectory.Text;
//为替换时受影响的控件设置属性
statuslabel.Text=“正在工作…”;
progbar.Value=0;
progbar.Visible=true;
btnprocess.Enabled=false;
btncancel.Enabled=真;
//开始在后台下载文件
backgroundWorker.RunWorkerAsync();
}
///
///在下载完成后设置控件的属性。
///
私有void去初始化进程()
{
//为操作时受影响的控件设置属性
statuslabel.Text=“就绪”;
progbar.Visible=false;
btnprocess.Enabled=true;
btncancel.Enabled=false;
}
///
///显示“目录浏览器”对话框。
///
私人无效浏览目录()
{
//创建新的文件夹浏览器对象
FolderBrowserDialog browser=新建FolderBrowserDialog();
//显示对话框
if(browser.ShowDialog(this)=DialogResult.OK)
{
//设置所选路径
txtDirectory.Text=browser.SelectedPath;
}
}
///
///验证用户输入是否完整。
///
///指示用户输入是否完成的值。
私有bool InputIsValid()
{
//将错误标志设置为false
bool-isError=false;
//清除所有错误
errorProvider.Clear();
//验证目录名
if(string.IsNullOrEmpty(txtDirectory.Text))
{
SetError(txtDirectory,“这是必填字段”);
是