我的bgworker有些问题。我想要完成的是我的bgworker报告将zip文件解压缩到我的文本框中的进度。
这就是我想要表现出来的方式:
5%
10%
15%
20%
25%
等等。
这是我到目前为止所得到的:
int percentage;
percentage = count*100/array.Length;
worker.ReportProgress(percentage);
我的文本框名称为ContentTextBox
。
这是可能有用的其余代码:
private void UnpackBackgroundWorkerCompletedEvent(object sender, RunWorkerCompletedEventArgs e)
{
FileTextBox.Text = databaseName;
ContentPanel.Visible = true;
Text = "Check Database";
}
public void UnpackWorker(object sender, DoWorkEventArgs doWorkEventArgs)
{
if (FileTextBox.Text == "")
{
MessageBox.Show("File textbox is empty");
return;
}
String fileName = FileTextBox.Text;
if (!File.Exists(fileName))
{
MessageBox.Show("File doesn't exist");
return;
}
Logger logger = new Logger(Path.ChangeExtension(FileTextBox.Text, ".log"), this, ContentTextBox);
String status = "******** Unpacking zipfile '" + fileName + "' ";
logger.Write("");
logger.Write("********");
logger.Write(status);
logger.Write("********");
string databaseFileName = Path.ChangeExtension(fileName, ".db");
DatabaseUtils.RestoreDatabase(fileName, databaseFileName);
logger.Write("Zipfile '" + fileName + "' unpacked to '" + databaseFileName + "'.");
databaseName = databaseFileName;
}
public void Run()
{
var unpackWorker = new BackgroundWorker();
if (FileTextBox.Text.EndsWith(".zip"))
{
unpackWorker.DoWork += UnpackWorker;
unpackWorker.RunWorkerAsync();
unpackWorker.RunWorkerCompleted += UnpackBackgroundWorkerCompletedEvent;
}
else
{ MessageBox.Show("No zip selected")
}
}
修改 要写入文本框,我必须使用logger.Write() 因为我创建了zip解包输出的日志文件。
提前感谢您的帮助/建议
答案 0 :(得分:0)
您应该处理BackgroundWorker.ProgressChanged
事件并在其中更新文本框。您也可以在调用RunWorkerCompleted
之前添加RunWorkerAsync()
事件处理程序,以避免潜在的竞争条件。
unpackWorker.DoWork += UnpackWorker;
unpackWorker.RunWorkerCompleted += UnpackBackgroundWorkerCompletedEvent;
unpackWorker.ProgressChanged += SomeMethodThatUpdatesYourTextBox
unpackWorker.RunWorkerAsync();