tags:

views:

584

answers:

4
+5  Q: 

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.

+13  A: 

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
DoEvents is evil. Use a Backgroundworker to do your job.
Andrei Rinea
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
+19  A: 

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
+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
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
+2  A: 

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
A: 

When it comes to a WPF application the situation is different and you need to thnk harder about the correct way to cope with doevents. The problem seems to me that doevents is sometimes a logical way to think about what is happening in your program - you start something off and want to resume processing when some event occurs - the fact that the language or system doesn't allow you to express this idea safely is another problem. See: Loading Bitmaps: DoEvents and the closure pattern