【发布时间】:2015-02-19 18:14:25
【问题描述】:
我为 BackgroundWorker 和进度条实现了“CheckFileSize()”函数,因为搜索任务可能需要很长时间。由于添加了 BackgroundWorker 线程,应用程序时间似乎要慢得多..我该如何优化,或者我做错了什么?
private void UploadApp()
{
label4.Visible = true;
label4.Text = ("Please wait...");
// Assign BackgroundWorker1 to start check file size.
backgroundWorker1.RunWorkerAsync();
}
// Check for invalid file size in 'AppID' folder.
private void CheckFileSize()
{
// Set application directory.
string AppDirectory = ("Z:/Projects/" + AppID);
// Set maximum file size in byte size (2GB).
long fileSizeLimit = 2000000000;
// Get IEnumerable (as in a list) on all files by recursively scanning directory.
var fileList = Directory.EnumerateFiles(AppDirectory, "*", SearchOption.AllDirectories);
// Retrieve the size of files.
long fileSize = (from file in fileList let fileInfo = new FileInfo(file) select fileInfo.Length).Sum();
// Exit application utility if maximum file size found.
if (fileSize >= fileSizeLimit)
{
//MessageBox.Show("Project folder '" + AppID + "' contain file size greater than or equal 2GB. Manual SCM upload required.");
DialogResult MsgResult;
MsgResult = MessageBox.Show("Project folder '" + AppID + "' contain file size greater than or equal 2GB. Manual SCM upload required.",
"Invalid File Size",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
Environment.Exit(0);
}
}
// BackgroundWorker1 runs 'DoWork' in the background to check invalid file size.
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
// Set for loop to increment progress bar.
for (int i = 0; i <= 100; i++)
{
CheckFileSize();
// Method to report the percentage complete.
backgroundWorker1.ReportProgress(i);
// Cancel BackgroundWorker1.
if (backgroundWorker1.CancellationPending)
{
break;
}
}
}
// Update the progress bar control when the worker thread reports progress.
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
// Enable START and EXIT button when work is done or thread is cancelled.
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
button1.Enabled = true;
button2.Enabled = false;
button3.Enabled = true;
}
}
【问题讨论】:
标签: c# performance optimization process backgroundworker