Programmerare, skeptiker, sekulärhumanist, antirasist.
Författare till bok om C64 och senbliven lantis.
Röstar pirat.
2008-12-13
The background worker component in .NET Framework is designed to make it easy to execute code in a separate thread. One purpose of writing multithreaded applications might be to allow an application to do heavy work without deteriorating the user experience. An example of this might be searching.
Imagine a form with a single threaded search routine. It might have a textbox for entering a search expression, a search button and a list view that displays the search result. The user is expected type the expression in, click the button and wait for the result.
A multithreaded solution might not require a search button, just a text box and a list view. It will also give the impression of being much faster than the single threaded version. This is how you do it, instead of just doing the search in the click event of the search button:
In the form, declare a Boolean variable that will keep track of the need for doing a search. You will also need a BackgroundWorker control.
In the TextChanged event of the text box, set the Boolean to true. Check if the background worker is already doing something (read the IsBusy property), and if it isn’t, restore the Boolean to false and start the worker. To start the worker call theRunWorkerAsync method of the background worker, and pass the content of the text box as an argument.
In the DoWork event of the background worker, do the search and present the result in the list view. There are a couple of things to keep in mind here.
Finally, in the RunWorkerCompleted event of the background worker, just restart the worker in the same way as you do on the TextChanged event of the text box, if required. (Check the flag, and restore it if you actually start the background worker again.)
This is what you must keep in mind when you present the result:
Have the search result stored in a member variable, so that it can be reached in both the procedure that populates it and the procedure that present it. Remember to call theBeginUpdate and EndUpdate methods of the list view control, to make the update fast. Also, remember that the actual presenting of the result must be done in the GUI thread (that is the main thread), not the thread started by the background worker. So write the code that uses the list view in a separate procedure, and call it using the Invoke method of the form. Pass in a delegate that point to the procedure. The code might look like this:
In the form, add the delegate:
Private Delegate Sub MyThreadSwitcher()
In the code that does the search, call the method that displays the result (in this example it is called RefreshResult) like this:
Dim X As New MyThreadSwitcher(AddressOf Me.RefreshResult)
Me.Invoke(X)
Categories: Visual Basic 8
Tags: Threading
Bjud mig på en kopp kaffe (20:-) som tack för bra innehåll!
Leave a Reply