-
Mar 8th, 2018, 02:43 PM
#1
Asynchronous Loading Form
I was recently working with a third party DLL that was absolutely terrible. I had a need to do something, wait until the operation was finished, and then do something else. Traditionally this is done in an event-driven programming language by doing something, waiting for the appropriate changed or completed event to be invoked, and then doing the "something else" in the respective event's sub routine. Unfortunately this particular third party DLL was notorious for invoking the same event multiple times which made the scenario in which I just described near impossible... or at least difficult through some ugly hacks. Since the first operation could take a bit of time to complete, I decided that what I wanted to do was do something, launch a responsive dialog indicating that the operation is doing its thing, and then have the dialog close when everything was finished; essentially I needed an asynchronous waiting dialog.
Luckily Visual Studio 2012 introduced a simplified approach to asynchronous programming via the Async/Await commands. What the code that I am providing does, is it creates a dialog Form with a PictureBox control that displays a GIF image of a spinning "wait" icon and a marquee style ProgressBar, runs a piece of code that may take a while to complete, and then returns the dialog result based on if the action was successfully completed or if it errored out:
Dialog Form:
Code:
Public Class FormLoading
Private _action As Action
Sub New(ByVal action As Action)
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
_action = action
End Sub
Private Async Sub FormLoading_Load(sender As Object, e As EventArgs) Handles Me.Load
Await Task.Run(_action)
Me.Close()
End Sub
End Class
You would then run the code using the following:
Code:
Try
'Crate a new instance of the FormLoading
Using frmLoad As FormLoading = New FormLoading(Sub()
'Do some long running task
Threading.Thread.Sleep(500) 'Zzz
End Sub)
'Show the dialog and wait for code to execute
frmLoad.ShowDialog()
End Using
'Do the next thing here....
Catch ex As Exception
'Do something with the error
End Try
Here is a screenshot of the loading Form to show you have simple it looks:
The animated GIF that I use, which is free to share and use commercially is: https://media.giphy.com/media/VlJkP9Vxi4nkI/giphy.gif
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|