简体   繁体   English

无法使用C#中的线程更新进度栏

[英]unable to update progress bar with threading in C#

    private void button1_Click(object sender, EventArgs e)
    {
        PROGRESS_BAR.Minimum = 0;
        PROGRESS_BAR.Maximum = 100;
        PROGRESS_BAR.Value = 0;

        for (int i = 0; i < 100; i++)
        {
            Thread t = new Thread(new ThreadStart(updateProgressBar));
            t.IsBackground = true;
            t.Start();
        }

    }

    private void updateProgressBar()
    {   
          PROGRESS_BAR.PerformStep();
          Thread.Sleep(4000);
    }

I always get this error: Cross-thread operation not valid: Control '' accessed from a thread other than the thread it was created on. 我总是会收到此错误:跨线程操作无效:从创建该线程的线程之外的其他线程访问了控件”。

I tried to search in google for solutions and unfortunately all of them didn't work for me. 我试图在google中搜索解决方案,但不幸的是,所有解决方案都不适合我。 does any one know how to solve this? 有谁知道如何解决这个问题? thanks in advance.. 提前致谢..

You cannot interact with UI elements from non-UI thread. 您无法与非UI线程中的UI元素进行交互。 You need to use code like 您需要使用类似的代码

this.BeginInvoke((Action)(() => PROGRESS_BAR.PerformStep()));

You should use the BackgroundWorker component and its ProgressChanged event. 您应该使用BackgroundWorker组件及其ProgressChanged事件。

You can call the ReportProgress method inside the DoWork handler (which runs on the background thread), then update the progress bar in the ProgressChanged handler (which runs on the UI thread). 您可以在DoWork处理程序(在后台线程中运行)中调用ReportProgress方法,然后更新ProgressChanged处理程序(在UI线程中运行)中的进度栏​​。

If you really want to do it yourself (without a BackgroundWorker), you can call BeginInvoke 如果您真的想自己做(没有BackgroundWorker),则可以调用BeginInvoke

All of your UI interaction, including callbacks, property sets, and method calls, must be on the same thread. 您的所有UI交互(包括回调,属性集和方法调用)都必须在同一线程上。

One of those callbacks can start another thread (or many threads) but they cannot directly update the UI. 这些回调之一可以启动另一个线程(或多个线程),但是它们不能直接更新UI。 The way to handle the updates are through data properties. 处理更新的方法是通过数据属性。 My processing thread would update a progress status property. 我的处理线程将更新进度状态属性。 This is throne read by the UI thread which has a timer for regular (100ms) updates of the progress bar. 这是UI线程读取的宝座,UI线程具有用于定期(100毫秒)更新进度条的计时器。

If you do this, you will need a lock on any objects which are used to communicate e status updates (eg. Strings). 如果这样做,您将需要在用于传达状态更新的任何对象(例如,字符串)上锁定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM