Events + Multi-Threading to Overcome Cross Thread Operation Error in VB.NET
Though VB is an object oriented language with multithreading I was always dissapointed with its less flexibility in using threads with the GUI. Of course many of you may have seen this InvalidOperationBlahException saying you cannot put up a progress bar/ timer./ count down iun a seperate thread while it interacts with the GUI. VB's solution was given as the background worker but I personally found it not-so-coordinate as well. So i thought of bringing up my own solutions. [Sure someother may have found it already but fot the sake of Googlers i'll continue with the tute :D]
The solution i came up is using the high support given to the Events by VB.NET.
Make a new project in VB.NEt and add a progressBar onto it and name it as " pbMain ".
In Form1 add this code.
Lets go code by code,
This makes a new event, as it names to fire up if a variable is changed.And the next block use Encapsulation like code for updating the the variable progress and note that in the Set method we raise the VariableChanged event.
Then in the form load we add a handler to handle the VaiableChanged Event if someone fired it. We direct the catching part to the progressChanged function and here's where the tricky part comes. In here we cannot just update the progressBar because they exists in separate threads, so we first check wheather it needed to be Invoked, if yes, we make a callBackRequest with the integer value we have back to the function, and this callBack calls the function as it is called by the Form1 thread or the main thread. So NO errors are given
Then we just make this threadAction mwthod to test the thing, it will update the progress variable value with an interval of 200 miliseconds. As the sleep() is given to the thread handling the progress, the main thread will work well without any hanging or stuff while the progress is updated.
THAT'S IT :D, by this mean you can add MANY THREADS so your customers will think your program is SUPER-FAST. This is juz a basic implementation but you can develop it into anything.
Hope ya'll enjoy threads :) cyah all
Visit my blog for more
|All times are GMT +5.5. The time now is 01:37.|