Okay so here’s the thing:
I have a linq query which loads approx. 1000 lines into a variable, during that process I want to display a progressbar, not necessarily stating the percentage, can be marquee style, doesnt matter.
This progressbar is on a modal form to precent the user from interacting with the app for the time the query’s running.
Now here’s my code:
Private Sub LoadBar()
Try
Dim load As New frmLoadbar
load.Text = "Loading bunch of data..."
load.ShowDialog()
Catch e As Threading.ThreadAbortException
Threading.Thread.ResetAbort()
End Try
End Sub
In another sub:
Dim myThreadDelegate As New Threading.ThreadStart(AddressOf LoadBar)
Dim th As New Threading.Thread(myThreadDelegate)
th.Name = "TimeConsuming"
th.Start()
Dim XY = db.Table.GetEnumerator
While XY.MoveNext
Dim item As New ListViewItem
item.Text = XY.Current.Name
item.Tag = XY.Current
ListBox1.Items.Add(item)
End While
Autos.Dispose()
Try
th.Abort()
Catch ex As Exception //here's where i 'swallow the re-thrown exception
End Try
Not thats one of the ugliest code i’ve ever written.It works i just dont want that rethrown exception.
Some explanation:
- I want the modal form to close after the query is done.
- For that reason I ‘abort’ the thread running the form.
- Since aborting a thread throws a double-exception i have to ‘swallow’
that exception.
Now i know i could implement this like the following:
- Coding a loop into the form holding the progressbar, which checks
periodically for a boolean’s value, and if its true the form could
close itself. - From the other form – on the worker thread – i could change that
booleans value to true after the query’s finished.
But here comes my question:
Whats the best way to implement this?
- I know it can be done with a background worker, which has been
specifically invented for this reason, but can i use the background
worker as the thread to show the progressbar? - If not (and i have to run the query on the background worker and
showing the modal form from my original form), would that mean that
the query would “work in the background”? - Would that mean that the query would be slower?
I’ve looked into other tutorials, but for one reason or another, either i wasnt able to copy it (due to complexity) or I wasn’t convinced that it was better than this.
Thank you for your time you took to answer.
Okay, so for future reference, if someone needs clear help with code samples, Microsoft has it (thats a first..)
You can download it here:
Multithreading