0

I am facing a problem in c#.

I have a form: Form1. The Form1 has a button which executes a loop in selenium c#. While this is running, the form freezes.

I want to show the progress (like 1/100, 2/100, ...) in a progressBar (progressBar1) in the same form. This value changes in the loop but does not show up in the UI, till the loop has finished. How do I achieve this?

--EDIT-- This question is about how to run the foreach loop in background so that the UI still responds. The form has more buttons and stuff, so the UI should be updated as well as the user should have access to other buttons. this cannot be possible is the loop freezes the program.

This is my code:

foreach (// condition)
{
    //do something

    //increment progress
    progressBar1.Value++;

}

  • What's the question? Did you [check the documentation?](https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.progressbar?view=windowsdesktop-7.0). What does `do something` actually do? If it freezes the UI, the UI won't be able to update itself. You'll have to use eg `await Task.Run()=>DoSomething())` to run that job in a background thread – Panagiotis Kanavos May 29 '23 at 07:35
  • `how to run the foreach loop in background so that the UI still responds`. It's `do something` that freezes the UI, not the loop. The actual solution is to run `DoSomething` in another thread. The easy way for the last 11 years is to use `await Task.Run(()=>DoSomething())`. 20+ years ago applications also called [Application.DoEvents](https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.application.doevents?view=windowsdesktop-7.0) between iterations to allow the UI to process events. The UI would still freeze between such calls – Panagiotis Kanavos May 29 '23 at 08:16
  • @PanagiotisKanavos shows our age that we still know about DoEvents ... – rene May 29 '23 at 08:58
  • The duplicate question does answer yours too if you read it carefully – mousetail May 30 '23 at 06:38

0 Answers0