Developing Long Running Tasks Using Asynchronous Programming with VB.NET 2005 - The solution is here
(Page 3 of 4 )
In the previous section, I showed you the problem, but didn’t give you a solution. Before giving you the solution, you need to understand the application execution a bit more in depth.
When an application is executed, it starts its own thread of execution (generally called the main/application thread). The application is closed when the thread is ended. Nevertheless, of any of number of instructions you embed within the application, all are executed in the same thread, one by one, in a hierarchical manner (sometimes even in the form of a top-down approach to execution).
If our application is trying to complete all the instructions in a task, it does so with a hell of a lot of speed. With this speed, it would not even find time to update the screen (even if we ask it to do so)!
The simplest solution is including a new simple statement as follows:
Private Sub ExecuteTask()
For i As Long = 1 To 100000
Me.lblMessage.Text = i
Application.DoEvents()
Next
End Sub
You can observe the statement “Application.DoEvents.” It really does the magic. Now, our application responds to the user in a professional manner. What exactly does this new statement do? During the execution of several instructions of a process/task, that simple statement pauses the application thread for a moment to handle user events (like updating the screen, handling mouse events, and so on).
Until now, it is quite perfect. The above method works quite well if you are working with several instructions. Let us consider the possibility that you are working on only one instruction from your application's point of view. The best example of this is the instruction “check for database connectivity.” It is really a simple instruction to check for the existence of a database. Now, the task's delay is not from our application. It is from an external source. Our application will not respond, unless the current instruction is completed (even though you use Application.Events). You cannot even close your application properly if it is frozen or unresponsive.
The second method (which I consider as the best) involves using a separate thread for the process and executing the same thread asynchronously with call backs for better presentation.
Next: The asynchronous way of dealing with a long task >>
More Visual Basic.NET Articles
More By Jagadish Chaterjee