Godfather
Godfather

Reputation:

DoEvents in .NET

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.

Upvotes: 11

Views: 49854

Answers (5)

arif
arif

Reputation: 55

simplest way is :

Application.DoEvents()

Thus you can call DoEvents

Upvotes: 2

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

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

Upvotes: -2

user27414
user27414

Reputation:

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.

Upvotes: 28

Jeff Yates
Jeff Yates

Reputation: 62377

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.

Upvotes: 17

dr. evil
dr. evil

Reputation: 27265

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.

Upvotes: 2

Related Questions