我有一个上传文件的后台任务,我希望它向另一个表单上的进度条报告进度。我该怎么做?我是 C# 的新手,但长期使用 VB .net 程序员。
我弄乱了这段代码,但它完全错了。
System.Windows.Forms.Form progForm = new ProgressWindows();
Control[] ctrls = progForm.Controls.Find("fileProgress1", true);
最佳答案
如果您使用的是 BackgroundWorker然后调用ReportProgress .否则,您需要将 UI 更改分派(dispatch)到正确的线程。在 WinForms 中查看 Control.InvokeRequired属性和相关方法。 WPF 等效项是 DispatcherObject.VerifyAccess .
编辑:Visual Studio 不在我面前,因此可能存在一些小的编译错误。
public partial class MyForm : Form
{
public MyForm()
{
InitializeComponent(); // fileProgress1 setup.
}
private void StartTask()
{
Task t1 = new Task(BackgroundMethod1, fileProgress1); // Explicitly pass a reference to the progress bar.
Task t2 = new Task(BackgroundMethod2); // Use a method that has access to the bar.
Task t5 = new Task(BackgroundMethod3, IncrementPBMethod); // Pass an action to the background method. Abstracting the physical progress bar as something where you can set the progress.
Task t4 = new Task(delegate() { /* fileProgress1 referened*/ }); // Create a closure. I don't recommend this method.
}
private static void BackgroundMethod1(ProgressBar pb)
{
for(int i = 0; i < 100; ++i)
{
if(pb.InvokeRequired)
{
pb.Invoke(delegate() { pb.Value = i; });
}
Thread.Sleep(1000);
}
}
private void BackgroundMethod2()
{
for(int i = 0; i < 100; ++i)
{
if(fileProgress1.InvokeRequired)
{
fileProgress1.Invoke(delegate() { fileProgress1.Value = i; });
}
Thread.Sleep(1000);
}
}
private static BackgroundMethod3(Action<int> setProgress)
{
for(int i = 0; i < 100; ++i)
{
setProgress(i);
Thread.Sleep(1000);
}
}
private void IncrementPBMethod(int value)
{
if(fileProgress1.InvokeRequired)
{
fileProgress1.Invoke(IncrementPBMethod, value);
}
else
{
fileProgress1.Value = value;
}
}
}
关于c# - 从函数更新另一个窗口中的 ProgressBar?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7302761/