【发布时间】:2014-05-03 11:53:44
【问题描述】:
我已经阅读了有关 Invoke(ing) 控件和诸如此类的内容......我不知道我应该调用哪些控件,因为我的主窗体和对话框窗体都有多个,因此我的问题在这里。我读过this 和this 和this ...我只是不明白如何将它应用到我的情况。是否有某个教程可供我阅读以尝试更好地理解?
我有一个 winform 应用程序 (C#) 可以完成一些工作。其中一些工作可能需要一段时间,所以我想我会提供一个进度对话框来提醒用户活动正在发生(而不是简单地依靠列表控件定期闪烁来指示更新)。
所以,我在我的项目中添加了一个新表单,添加了一些感兴趣的项目(要处理的项目数、预计完成时间、当前项目和整体进度条)。
public ProgressDialog Progress { get; set; }
public Form1()
{
Progress = new ProgressDialog(this);
InitializeComponent();
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.WorkerSupportsCancellation = true;
}
一旦单击 Process 按钮,我将主要工作设置为在后台工作人员中完成。
private void buttonProcess_Click(object sender, EventArgs e)
{
if (backgroundWorker1.IsBusy != true)
{
backgroundWorker1.RunWorkerAsync();
Progress.ShowDialog();
}
}
从在该线程上调用的方法,我在我的 ProgressDialog 表单上调用一个方法:
Progress.UpdateDialog(numFiles: filesToProcess.Count,
processTime: TimeSpan.FromTicks(filesToProcess.Count * TimeSpan.TicksPerSecond * 20)); // 20s is an estimated time, it will be updated after first file is processed.
那里有问题的代码(在 ProgressDialog.cs 中):
public void UpdateDialog(int percentComplete = 0, string fileName = "", int numFiles = 0, TimeSpan? processTime = null)
{
...
if (numFiles > 0)
{
labelNumFiles.Text = Convert.ToString(numFiles);
}
if (!processTime.Equals(null))
{
labelProcessTime.Text = Convert.ToString(processTime);
}
}
这会导致以下错误:
An exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll but was not handled in user code
Additional information: Cross-thread operation not valid: Control 'ProgressDialog' accessed from a thread other than the thread it was created on.
此外,主窗体有两个列表控件需要在处理文件时更新:已处理文件列表和错误文件列表。在我得到添加进度对话框的绝妙主意之前,一切正常。 LOL 那么,处理更新进度对话框的正确方法是什么?
【问题讨论】:
-
嗯,多线程基础可以帮助你...
-
您提供的第二个链接正是您所需要的。谷歌后台工作者 ProgressChanged,你会找到足够的帮助你。 (第二个链接stackoverflow.com/questions/2454900/…)
-
您在不到一个小时前提出了同样的问题,显然您已将其删除。您不应该删除然后一遍又一遍地重新提出相同的问题。正如我当时告诉你的那样,BGW 已经内置了对此的支持。
-
@Servy 我想我也已经看到了。
-
@Jon
ProgressChanged应该随着进度更新 UI。DoWork应该做工作而不是处理进度变化。
标签: c# winforms visual-studio-2010 user-interface