1

I use c# in winform.

Before a very heavy function, I want to show a waiting form to prevent the user. The form opens, but the controls in it are not drawn.

In the following code, waitingForm is a little form, with only a textbox and a progressbar

using (WaitingForm waitingForm = new WaintingForm())
{
  waitingForm.Show();
  HeavyFunction();
}

I see only two white rectangles, where the controls should appear. Why this happens ?

bubarnet
  • 101
  • 9

1 Answers1

2

You can't show the waiting form before the heavy processing and expect the UI to remain responsive. The thread that you're clogging up with HeavyFunction() is the same one that is responsible for drawing forms, controls and maintaining the UI. Use a BackgroundWorker or the ThreadPool to offload the heavy processing to another thread.

EDIT: Also, please consider Ron Beyer's input regarding async/await

Patrick Tucci
  • 1,824
  • 1
  • 16
  • 22
  • 1
    I agree with this except the recommendation for `BackgroundWorker` or `ThreadPool`. This is a good example of where to use async/await or Tasks. BackgroundWorker is effectively depreciated as well as working with low level threads except in specific circumstances. – Ron Beyer Jun 10 '15 at 17:32
  • @Ron Beyer Thanks, I wasn't aware of this. Edited to include link to async/await article on MSDN. – Patrick Tucci Jun 10 '15 at 17:34
  • I hope there was a simple solution like form.WaitForControlDrawn(). I look for the async/await solution, but it's a feature of Net 4.5. And I forgot to say that I need to target XP SP3, so I'm limited to Net 4.0. I already use backgroundworker, but it's a hugh work for a simple thing. I'm looking for ThreadPool instead. – bubarnet Jun 10 '15 at 23:09
  • I find that a NuGet package install the async/await functionnality for .Net4.0. I'm looking for those functions. – bubarnet Jun 11 '15 at 00:11