3

If I'm looping through a prolonged operation (say, processing files) and I want to update a progress bar, I need to use DoEvents, from what I can understand.

But calling it during every loop of the function only results in the progress bar's animation being played back really fast (or slow, depending on the operation). I understand that this is because DoEvents allows the progress bar to "breathe", for lack of a better word, causing it and the rest of the form to refresh.

My question is, how do you know that it's appropriate to call DoEvents? Obviously you can't just call it on a whim however-often you feel like it - this results in sporadic animations, among other things. So is there some quick method to check if a form/application needs a DoEvents called?

qJake
  • 16,821
  • 17
  • 83
  • 135

3 Answers3

8

Oh, duh - I just smacked myself.

I should just use a background thread to process, and leave the UI thread alone.

qJake
  • 16,821
  • 17
  • 83
  • 135
  • 1
    `Application.DoEvents();` does exist, however it's discouraged to actually use it extensively, it's only there for legacy support, or so I've read. – qJake Nov 07 '10 at 23:04
  • indeed it is. And because of the support of legacy VB code to be a little more precise. IIRC that is. – jcolebrand Nov 07 '10 at 23:42
  • Yeah, VB5/6 has `DoEvents` (yep, just like that) within a form, which does exactly this. – qJake Nov 08 '10 at 00:03
1

If you don't want to fiddle around with threads and you don't mind a little beta-testing, the Visual Studio Async CTP might be worth a look -- it's basically "DoEvents done the right way" (and more).

For an introduction to these new async features, I recommend to check out Eric Lippert's blog.

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Heinzi
  • 167,459
  • 57
  • 363
  • 519
  • "DoEvents the right way" is a nice way to describe it. I might steal that. :-) FYI, I have not yet covered how to do async tasks with notifications (like progress bars and so on). I hope to do so in a future episode. – Eric Lippert Nov 09 '10 at 00:58
  • @Eric: Be my guest! And I'm looking forward to reading that episode... :-) – Heinzi Nov 09 '10 at 10:28
1

Instead of messing around with threads, you can use a BackgroundWorker. It simplifies performing work and updating controls on a Form as you cannot update a UI Control directly from a non-UI thread. The example in the docs updates a Label control, but you can easily modify it to use a ProgressBar.

Tergiver
  • 14,171
  • 3
  • 41
  • 68
  • Yes, this is true, however my "worker" thread actually needed to update a lot more - about 5 labels and a progress bar. It was easier to use threading and `Invoke()` in this instance, but for simpler implementations, a `BackgroundWorker` would certainly be useful. – qJake Nov 08 '10 at 19:41