How do I let the function in a form run in the background without slowing down/stopping my entire application until it has finished?
Printable View
How do I let the function in a form run in the background without slowing down/stopping my entire application until it has finished?
Well, you could do it as easily as this:
vb Code:
Dim t As New Thread(Address Of MyFunction) t.Start()
Which will work, but if you're accessing controls from the function, there will be some issues.
The simple answer is that you need to execute the method on a secondary thread. There are various ways to make that happen, including as WD has shown. Multi-threading does introduce complexity though.
One way that that complexity can be minimised is to use a BackgroundWorker, which hides multi-threading behind a familiar "call a method, handle an event" facade. If you want to learn how to use a BackgroundWorker, follow the CodeBank link in my signature and check out my post on the subject.
Also, if you explain exactly what you're trying to achieve then we can advise the best way to achieve it, which may be as WD suggested, a BackgroundWorker or something else.
My form contains 6 charts. This form will now be loaded on application startup into the MDIParent. I'm loading yesterdays data from a very busy D3 database which takes about 15 seconds. Now currently when the application starts, for that 15 seconds you can't use the application. I need this to load and generate on its own time while the user will be able to use the application immediately.
This may be a little trickier than you think, although certainly not impossible. As WD said, accessing controls makes things more complicated, because that is inherently a foreground operation.
Without knowing more about your app, my best guess is that a BackgroundWorker would be the way to go. You can call RunWorkerAsync and pass any data required by the data access code as an argument.
You perform the data access in the DoWork event handler, querying the database and populating a DataSet. You then make that DataSet the result, which you then use in the RunWorkerCompleted event handler to update the UI. For a full example, check out the aforementioned CodeBank submission. It demonstrates both passing data in and out of the background task, i.e. the DoWork event handler.
The form is still loaded on startup, but the function that populates the chart is in the 2nd thread. ERROR
vb.net Code:
Dim TRD1 As New Threading.Thread(AddressOf LOAD_CHART1) TRD1.Start()
Attachment 83123
Ok jmcilhinney, Will do. Thanks
This is exactly what both WD and myself were talking about. You cannot update the the UI in the background thread because the UI is the very definition of foreground. This is not a problem though because updating the UI is not the slow part. Getting the data to update the UI with is the slow part. That's what you do in the background and then you switch to the UI thread to update your control(s).