earthandfire
Programmer
There seems to be a lot of emotion regarding whether or not it is valid to use Application.DoEvents
The following code block is a time consuming process:
To run this:
Two things:
(1) The program is unresponsive
(2) If the user clicks on the disabled button the code will run again (once for each click) despite it supposedly being disabled.
If ProcessTakingALongTime is spun off onto a separate thread, the program will become responsive, however the code will repeatedly run (once for each click).
Judicious use of Application.DoEvents solves both problems:
gives an unresponsive program (unless multi-threaded) but processes the message queue before re-enabling the button.
gives a responsive program, if the user does happen to click on the disabled button, nothing will happen.
I would be interested to know what those who advocate not using Application.DoEvents would do in this situation.
By the way, this phenomenon or feature was discussed in detail in thread102-1068694
The following code block is a time consuming process:
Code:
Private Sub ProcessTakingALongTime()
For a As Integer = 1 To 10
For b As Integer = 1 To 100000000
'do something really important here
Next
'simulate a progress bar
Label2.Text = a.ToString
Label2.Refresh()
Next
End Sub
To run this:
Code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Button1.Enabled = False
ProcessTakingALongTime()
Button1.Enabled = True
End Sub
Two things:
(1) The program is unresponsive
(2) If the user clicks on the disabled button the code will run again (once for each click) despite it supposedly being disabled.
If ProcessTakingALongTime is spun off onto a separate thread, the program will become responsive, however the code will repeatedly run (once for each click).
Judicious use of Application.DoEvents solves both problems:
Code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Button1.Enabled = False
ProcessTakingALongTime()
Button1.Enabled = True
Application.DoEvents()
End Sub
gives an unresponsive program (unless multi-threaded) but processes the message queue before re-enabling the button.
Code:
Private Sub ProcessTakingALongTime()
For a As Integer = 1 To 10
For b As Integer = 1 To 100000000
'do something really important here
Next
'simulate a progress bar
Label2.Text = a.ToString
Label2.Refresh()
Application.DoEvents()
Next
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Button1.Enabled = False
ProcessTakingALongTime()
Button1.Enabled = True
End Sub
gives a responsive program, if the user does happen to click on the disabled button, nothing will happen.
I would be interested to know what those who advocate not using Application.DoEvents would do in this situation.
By the way, this phenomenon or feature was discussed in detail in thread102-1068694