0

I have a mainform with a simple button to test my loading screen.

enter image description here

public partial class MainForm : Form
{
    public MainForm()
    {
        InitializeComponent();
    }

    private void loadingscreenTest(object sender, EventArgs e)
    {
        int count = 100;
        LoadingScreen f2 = new LoadingScreen(0, count, 1);
        f2.Show();
        //Application.DoEvents();
        for (int i = 0; i < count; i++)
        {
            System.Threading.Thread.Sleep(1000);

            f2.performstep();
        }
    }
}

LoadingScreen is a simple form with a ProgressBar on it.

enter image description here

It's code is the following:

public partial class LoadingScreen : Form
{
    public LoadingScreen(int current, int max, int step)
    {
        InitializeComponent();
        this.progressBar1.Maximum = max;
        this.progressBar1.Step = step;
        this.progressBar1.Value = current;
    }

    public void performstep()
    {
        this.progressBar1.PerformStep();
    }
}

I know that you are not supposed to run long running processes in the UI thread, however in this scenario i can't see why is it that when i press the button, the LoadingScreen form has trouble drawing its content without the Application.DoEvents call. Can you please help me understand this phenomenon?

The Issue persists for like 1 to 2 seconds but what is buggin me is that I don't understand why.

I am using Visual Studio 2010 and .Net 4.0

enter image description here

Attila Horváth
  • 562
  • 1
  • 5
  • 16
  • 2
    *"why is it that when i press the button, the LoadingScreen form has trouble drawing its content without the Application.DoEvents call"*, because when you call `f2.Show()` in UI thread, you are not yet release it for draw. So no draw, until you explicitly call [`PerformStep`](https://msdn.microsoft.com/en-us/library/system.windows.forms.progressbar.performstep(v=vs.110).aspx), which internally calls invalidate and repaint the form for the first time. Notice, you are still not allow any user interaction with this form. Try to exchange `Sleep` and `PerformStep` to see some difference.. – Sinatr Nov 14 '16 at 16:22
  • When you are blocking UI thread be ready for ugly solutions (like calling `DoEvents` one). – Sinatr Nov 14 '16 at 16:25
  • 1
    You could throw the progress into another thread and have it callback to the main form for update. This would keep your UI thread available for the call. – vipersassassin Nov 14 '16 at 16:55
  • http://stackoverflow.com/questions/4698080/spawn-a-new-thread-to-open-a-new-window-and-close-it-from-a-different-thread – vipersassassin Nov 14 '16 at 16:56
  • Sinatr Your answer is quite helpful, could you please direct me to a page where this behaviour of winforms in documented? It's as you've said, however the LoadingScreen window only recieves the WM_PRINTCLIENT message when the 2nd PerformStep is being called. – Attila Horváth Nov 14 '16 at 19:31

0 Answers0