If you are a programmer, if you like coding and if you love challenging typical programming rules, then this post is for you. Actually this post originated from a tragedy. Which is that every algorithm I write for my task, involves enormous calculations. Sometimes the calculations grows even worse that it starts blocking my GUI. This give wrong message of coding flaw, and is not user interactive indeed. To handle the situation, I encountered a class called “the Background Worker”.
This class provide the facility to do tasks in the background, in another thread other then main thread, thereby preventing blocking of the User Interface. You can get the full overview on how to do so in the following post, the BackgroundWorker. Continuing from the post onward, there are times when you need to assign the result of the calculation from inside the worker, directly to a textblock or a label or a textbox, whatever, which is their on your user interface or instead assigning the result to the properties which are bind to one of your user control. In both cases you will get “Invalid cross thread exception”. Cause you are trying to access the component of another thread. In this case, you are trying to access the component of UI thread from background worker thread.
Here, I have a label and I tried to set it’s content from within the worker. Since worker is basically another thread, so I got the Unauthorized access exception.
1: _bWorker.DoWork += (sender,e) =>
2: {
3: lblName.Content = "Neelma";
4: };
So, in order to do that, I write it within the action of Dispatcher’s Begin Invoke. So I have,
1: _bWorker.DoWork += (sender,e) =>
2: {
3: Dispatcher.BeginInvoke(() =>
4: {
5: lblName.Content = "Neelma";
6: });
7: };
This will only work for the case when you are accessing UI thread’s component from another thread.
0 comments