11

What's the equivalent of the VB6's DoEvents in .NET?

EDIT:

I have a Sub that takes a long time to do its work. (it has a do-while) when I call it, The form turns white. in VB6 I used to put a DoEvents in the method (inside its do-while) to prevent this.

  • 2
    Consider also BackgroundWorker instead of DoEvents. DoEvents is (for good reasons) considered a bad practice. – Andrei Rînea May 04 '09 at 15:50
  • I don't agree that it's considered bad practice - it's bad in the wrong situations and I would certainly consider it a code smell, but there are legitimate uses. – Jeff Yates May 04 '09 at 17:59

5 Answers5

28

There are few (if any) cases in which DoEvents is the right solution in .NET. If you post a little about what you're doing, we might have some suggestions as to an alternative.


In response to your edit, what you need to do is create a BackgroundWorker. This will keep your main (GUI) thread free, allowing it to repaint and behave normally. There are many tutorials on the web for this, including this one.

Jon B
  • 51,025
  • 31
  • 133
  • 161
  • 4
    +1. I agree; whenever i see or hear about DoEvents in .NET code, i see a warning flag that there is a design issue to take care about. – Fredrik Mörk May 04 '09 at 15:10
  • 1
    I've seen game loops that use DoEvents quite a bit. In that instance it doesn't seem to be an altogether bad idea. – Dinah May 04 '09 at 16:50
18

Application.DoEvents() should be what you're looking for.

However, note the following (from the linked MSDN page):

Unlike Visual Basic 6.0, the DoEvents method does not call the Thread.Sleep method.

Update

Given that the questions now provides an explanation of usage, I would say refactoring to use a background thread would be a better solution. DoEvents can lead to some issues as it will cause the underlying message queue to pump, which can lead to re-entrancy and a whole host of other side-effects. DoEvents has valid use-cases and I would shy from saying that it's use is bad practise - it exists for valid reasons - but in most cases, there are better solutions than just calling DoEvents.

Jeff Yates
  • 61,417
  • 20
  • 137
  • 189
  • 3
    It's only evil if used inappropriately and without an understanding of what is happening. Ignorance of how Windows pumps messages is no excuse and spawning new threads just to avoid learning is equally bad. – Jeff Yates May 04 '09 at 16:39
2

simplest way is :

Application.DoEvents()

Thus you can call DoEvents

Gunaseelan
  • 2,494
  • 5
  • 36
  • 43
arif
  • 45
  • 1
  • 7
2

Other answers are correct, aS a side note If you need to use DoEvents() consider using BackgroundWorker or Control.Invoke . 99% of the time DoEvents() indicates some dirty hack.

dr. evil
  • 26,944
  • 33
  • 131
  • 201
-2

For those who think DoEvents is evil just use this instead:

System.Windows.Forms.Application.ThreadContext.FromCurrent.RunMessageLoop(2, Nothing)