views:

1054

answers:

4

I currently have a program that runs several "intense" queries. I added a textbox and presented status updates when a query was starting, eding and how many were left. This would suite my need, but the textbox doesn't actually display anything until all the queries are finished. It then displays all the updates at once. I'm assuming updating the textbox in another thread would solve this issue, and that is where I am lost. How can I use a thread that receives a message from the main form running the query and have it display it in the textbox?

+4  A: 

The BackgroundWorker component suits your need (sample code is there in the MSDN link). You handle its DoWork event and perform the actual query in it. You report the progress by calling its ReportProgress method. To display the reported progress, you should handle its ProgressChanged event and update the UI. You start the job by calling the RunWorkerAsync method of the background worker. Using BackgroundWorker relieves you from manually starting and stopping threads and communicating with the UI thread to update the progress bar.

Mehrdad Afshari
haha, i was just going to say that. i can never seem to answer fast enough.
Jugglingnutcase
Hah, I didn't even think of doing the query in a different thread. I'll try that.
Shawn
@Jugglingnutcase - I always have the same problem! The other day I answered a question with the exact same answer pointing to the same url as somebody else, but he was 5 seconds quicker than me lol
Dave7896
@Dave7896 Doesnt seem to stop other people from answering the same thing though does it?
Jugglingnutcase
A: 

The easiest way to do this is making use of BackgroundWorker, handling it's DoWork event and reporting progress to the ProgressBar with ProgressChanged event.

to start:

worker.RunAsync()

report progress:

worker.ReportProgress(10) 'for 10%
Alex LE
A: 

Adding to what Mehrdad and Alex posted, here's how to handle the event raised by the ReportProgess method (ProgressChanged) to update the progress bar:

Private Sub backgroundWorker_ProgressChanged ByVal sender As Object, ByVal e As ProgressChangedEventArgs) Handles backgroundWorker.ProgressChanged

    Me.progressBar1.Value = e.ProgressPercentage

End Sub
fatcat1111
+1  A: 

BackgroundWorker is a good general-purpose method for doing intensive work on a background thread. But, since your question sounds like you are doing database operations, it might be easier to use the native support for asynchronous operations in ADO.Net. You could use callbacks for the progress bar.

MarkJ