unable to update progress bar with threading in C#

前端 未结 3 906
一生所求
一生所求 2021-01-23 15:44
    private void button1_Click(object sender, EventArgs e)
    {
        PROGRESS_BAR.Minimum = 0;
        PROGRESS_BAR.Maximum = 100;
        PROGRESS_BAR.Value = 0;

          


        
相关标签:
3条回答
  • 2021-01-23 15:58

    All of your UI interaction, including callbacks, property sets, and method calls, must be on the same thread.

    One of those callbacks can start another thread (or many threads) but they cannot directly update the 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.

    If you do this, you will need a lock on any objects which are used to communicate e status updates (eg. Strings).

    0 讨论(0)
  • 2021-01-23 16:08

    You should use the BackgroundWorker component and its ProgressChanged event.

    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).

    If you really want to do it yourself (without a BackgroundWorker), you can call BeginInvoke

    0 讨论(0)
  • 2021-01-23 16:10

    You cannot interact with UI elements from non-UI thread. You need to use code like

    this.BeginInvoke((Action)(() => PROGRESS_BAR.PerformStep()));
    
    0 讨论(0)
提交回复
热议问题