我想为加载 XML 数据的过程使用一个后台线程,可能带有一个进度条,让用户知道应用程序正在积极地做某事。
我通过搜索网络编写了这段代码。
当用户点击浏览按钮时,我想在 winform 的 TreeView 中加载一个 XML 树。
如果是大型 XML 文件,winform 会卡住。所以为了让用户知道在后台工作正在进行,我想添加一个进度条。我在这里使用了后台 worker 。
但它在 xmlDocument.Load(txtFileName.Text); 上引发 System.ArgumentException 异常,显示此消息“URL 不能为空。\r\nParameter name: url”; 这一行。
我的 xml 文件格式正确,并且位于我选择的正确位置。
但我无法找到此异常的原因。
你能帮忙或告诉我代码中的更正吗?
谢谢....
private void btnBrowse_Click(object sender,EventArgs e)
{
bgWorker1.RunWorkerAsync();
StripProgressBar.Value = 0;
toolStripStatusLabel1.Text = "Browsing for a Xml file";
if (open.ShowDialog(this) == DialogResult.OK)
{
txtFileName.Text = open.FileName;
initiatingTree(open.FileName); //this variable gives the name of selected file
}
while (this.bgWorker1.IsBusy)
{
StripProgressBar.Increment(1);
// Keep UI messages moving, so the form remains
// responsive during the asynchronous operation.
Application.DoEvents();
}
}//Browse button
private void bgWorker1_DoWork(object sender, DoWorkEventArgs e)
{
xmlDocument = new XmlDocument();
Thread.Sleep(5000);
xmlDocument.Load(txtFileName.Text);
btnBrowse.Enabled = false;
}
private void bgworker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// Set progress bar to 100% in case it's not already there.
StripProgressBar.Value = 100;
if (e.Error == null)
{
MessageBox.Show(xmlDocument.InnerXml, "Download Complete");
}
else
{
MessageBox.Show("Failed to download file");
}
// Enable the Browse button and reset the progress bar.
this.btnBrowse.Enabled = true;
StripProgressBar.Value = 0;
toolStripStatusLabel1.Text = "work finished processing request.";
}//workerCompleted
最佳答案
当用户单击“浏览”时,您将通过调用
立即启动异步过程bgWorker1.RunWorkerAsync();
这会调用后台工作程序的 DoWork
方法,它会休眠 5 秒,并从 txtFileName.Text
中提取值,无论用户是否已完成输入在 FileOpenDialog
中。
您最好将 byWorker1.RunWorkerAsync()
(以及忙碌的等待)移动到 if (open.ShowDialog(this) == DialogResult.OK)
block 。
private void btnBrowse_Click(object sender,EventArgs e)
{
StripProgressBar.Value = 0;
toolStripStatusLabel1.Text = "Browsing for a Xml file";
if (open.ShowDialog(this) == DialogResult.OK)
{
txtFileName.Text = open.FileName;
initiatingTree(open.FileName);
bgWorker1.RunWorkerAsync();
while (this.bgWorker1.IsBusy)
{
StripProgressBar.Increment(1);
// Keep UI messages moving, so the form remains
// responsive during the asynchronous operation.
Application.DoEvents();
}
}
}
对于这些类型的问题,在文件将要加载的地方放置一个断点可能会有所帮助,并查看发生这种情况时的值是什么......您可能会注意到它被调用为空字符串.
您还可以考虑带有参数的 RunWorkerAsync
版本;您可以通过这种方式传递文件,而不是尝试从文本框中异步读取它。
就我个人而言,我不会使用调用 Application.DoEvents()
的循环;相反,我会将控制权返回给 UI 线程,然后从异步线程 Invoke()
到它以影响进度条更新。
关于c# - 上传xml文件进度条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/602394/