c# - 从函数更新另一个窗口中的 ProgressBar?

标签 c# .net winforms progress-bar

我有一个上传文件的后台任务,我希望它向另一个表单上的进度条报告进度。我该怎么做?我是 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/

相关文章:

winforms - 将自定义视觉样式 (.msstyle) 应用到单个 Winforms 应用程序

c# - 新建具有非常大初始容量的 List<T> 并填充它与简单地填充 LinkedList<T> 的性能

c# - 声明了变量 'MyException' 但从未使用过

C# 窗体 : Set text in ComboBox based on selected Item

winforms - 更改 Winform ListView 标题的背景颜色

c# - 当一个对象从一个方法返回时,是创建了一个新的实例还是一个引用?

c# - 哪种 SQL Server 字段类型最适合存储价格值?

c# - ASP.NET:具有快速回发的动态多提交按钮

c# - 将 protobuf-net 与 WCF 和 Silverlight 结合使用

c# - 发布到 azure 时出现 System.NullReferenceException