UI Container in thread? - c#

brothers in code.
I'm trying to make my WinForms app multi threaded. In DoWork of my background worker I've got a method which changes few controls using MethodInvoker delegate. My question is if I have to invoke every control every time I want to change it from another thread or maybe there is some kind of container of controls which I can invoke to avoid multiple invoking certain controls?

Invoking means scheduling your code to run on the thread that owns the controls, which in all straightforward cases would be the very same thread for all of your controls. So while you do have to invoke every time you want to interact with a control, you can in practice "pool" as many interactions as you wish together and only invoke once for the whole piece (doing so will be more performant).
If you want to "hide" the invocations you 'd have to write a class that, when triggered, would detect changes to its properties and use Invoke on code that interacts with your controls in a manner dependent on these properties. So the workflow would be:
Your worker modifies the "controller"'s properties, without invoking. This does not have any immediate effect.
At some point, the controller is "triggered" (perhaps periodically by the worker?).
The controller detects (or already knows) what changes were made to its properties and how these translate to invoking code on controls. It invokes a block of code that interact with the controls accordingly.

My question is if I have to invoke every control every time I want to change it from another
thread or maybe there is some kind of container of controls which I can invoke to avoid multiple
invoking certain controls?
You have to invoke every time yiou want to change the UI. The invoke operation can do more than changing one peroeprty -it can be a complete function udpating 100 controls.
Minimizing invokes is good for performance.
No, there is no predefined container. You are assumed to be an able program an invoke, for example for an anonymous code block, yourself.

Let's say you want to change the text on two Labels. Assuming they belong to the same Form, you can do this either by individual calls to Invoke...
void buttonInvoke_Click(object sender, EventArgs e) {
Invoke((Action)(() => label1.Text = "A1"));
Invoke((Action)(() => label2.Text = "A2"));
}
...or by grouping then in a single Invoke, to save some typing and increase performance.
private void buttonInvoke_Click(object sender, EventArgs e) {
Invoke(
(Action)(() => {
label1.Text = "B1";
label2.Text = "B2";
})
);
}

Technically all of your GUI is created on the main thread, so If you invoke say a main panel on the GUI then within that invocation method you can alter other controls on the GUI all within that method
Plus if your background worker was created on main thread then you can call report progress event back on main thread... Which means invocation not required. Main purpose of background workers really.

public void UpdateControl<T>(T control, Action<T> action) where T : Control
{
if(control.InvokeRequired)
control.Invoke(() => action(control));
else
action(control);
}

Related

WPF Pass TreeView to a backgroundworker's DoWork method

I'm trying to access the header properties of a TreeView control in a background worker's DoWork method.
I have tried the following:
var worker = new BackgroundWorker();
worker.DoWork += DoWork;
worker.RunWorkerAsync(MyTreeView);
private void DoWork(object sender, DoWorkEventArgs e)
{
var x = (e.Argument as TreeView);
var item1 = x.Items[0] as TreeViewItem;
//error here..
var headerItem1 = item1.Header;
}
The error that is thrown says that the property I want to access is owned by another thread (the UI thread in my case).
I have had this problem only with the TreeView control so far. Passing and then accessing less 'complex' controls like Labels or TextBlocks has worked fine.
Thanks for every answer.
The rule is: only access the GUI elements (controls) on the GUI thread.
In a BackgroundWorker, the DoWork event handler will be called on a background thread. You are not allowed to access the GUI elements on that thread. Accessing means reading or writing properties (or indexers) or calling methods.
If you need to do something with a control on a background thread, use Dispatcher.Invoke method. But be warned, that using the Invoke/BeginInvoke methods might impact the overall performance (e.g. when used in a tight loop).
You have to redesign your logic in such a manner that you don't need to access the GUI elements on a background thread. This would be the best solution.
By the way, I would recommend you to move from the BackgroundWorker to the modern asynchronous patterns (async/await & Tasks).

How resource efficient is Data Binding vs BeginInvoke (for the purpose of GUI manipulation)

I did a search and this is the closest thing to the question I have in mind
How do I refresh visual control properties (TextBlock.text) set inside a loop?
The example included in that URL is exactly like in my situation, except that I am reading in a constant changing stream of data, and want the changes in values to be reflected in the Windows interface.
I am trying to make the program as efficient as possible, so should I use
(INotifyPropertyChanged + Data Binding)
or following would be better?
Application.Current.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Background,
new Action () => Label1.Content = some_content))
Assuming I perform a lot of buffer/checksum operations using system timers.
WPF, like most other UI frameworks, requires that you modify UI controls from the same thread on which they were created. This thread, often referred to as the "UI thread", is usually the application's main thread, i.e. the one where program execution started.
If you happen to subscribe to the SerialPort.DataReceived event, you are facing a problem, because that event might be triggered on any (background) thread:
The DataReceived event is raised on a secondary thread when data is received from the SerialPort object. Because this event is raised on a secondary thread, and not the main thread, attempting to modify some elements in the main thread, such as UI elements, could raise a threading exception. If it is necessary to modify elements in the main Form or Control, post change requests back using Invoke, which will do the work on the proper thread.
Meaning that inside your event handler, you may not directly manipulate any UI controls.
That is where WPF's Dispatcher.BeginInvoke comes in: It helps you to get some code back on the UI thread. You pass it a delegate, and that delegate will be invoked on the UI thread. Therefore you are allowed to manipulate the UI inside that delegate.
Data binding is no real alternative to BeginInvoke: Data binding also manipulates the UI, based on changes to some data object (or vice versa), but it does not automatically switch to the UI thread. This means that if you're using data binding, you must change the data context only if you're on the UI thread... so you need BeginInvoke anyway.
That all being said, if the use of data binding makes your code simpler and easier to understand, by all means use it! But you might still need Dispatcher.BeginInvoke:
private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
Application.Current.Dispatcher.BeginInvoke(..., () => dataContext.SomeProperty = serialPort...;
}

Form Visiblity Problem

Form1.button_Click(...) {
// Show a dialog form, which runs a method <CheckBalance()> on it's OnLoad Event.
var modemDialog = new ModemDialog("COM25");
modemDialog.ShowDialog();
// the user can't see this dialog form until the method <CheckBalance()> terminates.
}
Is it possible to show first the dialog then run the specified method?
THanks.
That is correct and expected. Winforms UI is inherently single-threaded. Having a function call like "CheckBalance" in the form load event will prevent the form from showing until the form load event completes. Depending on the duration of the task, you have a number of options available to you:
If it's a fast task, compute it ahead of time before showing the form
If it's something the user may want to initiate, move it to a button on the new form, so it's only calculated on the request of the user
If it's a long running task that takes some time, you'll need to move it off in to another thread. Using a BackgroundWorker is recommended.
OnLoad occurs before the form is shown to allow you to initialise the form and variables and what not, which means it is synchronous. The form will not show until you return from that function.
If you want to asynchronously run the CheckBalance() method, then you can use a few techniques, such as utilising the Threading, ThreadPool or Tasks API to shift that work to a background thread, and returning immediately so that the form is shown.
Here is an example of using a Task to perform the same action, but asynchronously so that the form immediately shows:
Action<object> action = () => { CheckBalance(); };
new Task(action).Start();
Please note that if you access the UI thread, you'll need to beware of thread-safety and invocation.
The simple way to make sure your form is visible before CheckBalance is run is to use this code in the form load handler:
this.BeginInvoke((Action)(() => this.CheckBalance()));
This will push the execution of the CheckBalance method onto the UI thread message pump so will execute after all preceding UI code is complete.
Others are correct though that the UI will still be blocked as CheckBalance executes. You probably want to run it on a background thread to prevent this.

When Something Occurs in a BackgroundWorker, Trigger Code on a Different Thread?

I have a background worker that runs and looks for stuff, and when it finds stuff, I want to update my main WinForm. The issue that I'm having is that when I try to update my WinForm from my background worker, I get errors that tell me I can't modify things that were made outside of my background worker (in other words, everything in my form).
Can someone provide a simple code example of how I can get my code to work the way I want it to? Thanks!
I believe you're looking for the OnProgressChanged Event. More info with example here: http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.onprogresschanged.aspx
If I understand correctly, you want to make a change on the form itself, however you cannot change a control on a form from a thread other than the thread the form was created on. To get around this I use the Form.Invoke() method like so:
public void DoSomething(string myArg)
{
if(InvokeRequired)
{
Invoke(new Action<string>(DoSomething), myArg);
}
else
{
// Do something here
}
}
The InvokeRequired property checks the calling thread to determine if it is the proper thread to make changes to the form, if no the Invoke method moves the call onto the form's window thread.

Delay loading of combobox when form loads

I've got a Windows Forms (C#) project with multiple comboboxes/listboxes etc that are populated when the form loads.
The problem is that the loading of the comboboxes/listboxes is slow, and since the loading is done when the form is trying to display the entire form isn't shown until all the controls have been populated. This can in some circumstances be 20+ seconds.
Had there been a Form_finished_loaded type of event I could have put my code in there, but I can't find an event that is fired after the form is done drawing the basic controls.
I have one requirement though - the loading has to be done in the main thread (since I get the items from a non-threading friendly COM-application).
I have found one potential solution, but perhaps there is a better way?
I can create a System.Timer.Timer when creating the form, and have the first Tick be called about 1 second later, and then populate the lists from that tick. That gives the form enough time to be displayed before it starts filling the lists.
Does anyone have any other tips on how to delay the loading of the controls?
There is the Shown event that "occurs whenever the form is first displayed.". Also you may want to use the BeginUpdate and EndUpdate functions to make the populating of your combobox faster.
It has that certain smell of workaround, but this approach should fulfil your needs:
private bool _hasInitialized = false;
private void Form1_Shown(object sender, EventArgs e)
{
if (!_hasInitialized)
{
ThreadPool.QueueUserWorkItem(state =>
{
Thread.Sleep(200); // brief sleep to allow the main thread
// to paint the form nicely
this.Invoke((Action)delegate { LoadData(); });
});
}
}
private void LoadData()
{
// do the data loading
_hasInitialized = true;
}
What it does is that it reacts when the form is shown, checks if it has already been initialized before, and if not it spawns a thread that will wait for a brief moment before calling the LoadData method on the main thread. This will allow for the form to get painted properly. The samething could perhaps be achieve by simply calling this.Refresh() but I like the idea of letting the system decide how to do the work.
I would still try to push the data loading onto a worker thread, invoking back on the main thread for populating the UI (if it is at all possible with the COM component).
Can you get your data from a web service that calls the COM component?
That way, you can display empty controls on a Locked form at the start, make Asynchronous calls to get the data, and on return populate the respective combos, and once all of them are loaded, you can unlock the form for the user to use.
You could listen for the VisibleChanged event and the first time it's value is true you put your initialization code.
Isn't FormShown the event you're looking for?
When you say that you cannot use a background thread because of COM what do you mean? I am using many COM components within my apps and running them on background threads.
If you create a new thread as an STAThread you can probably load the ComboBox/ListBox on a Non-UI thread. IIRC the ThreadPool allocates worker threads as MTAThread so you'll need to actually create a thread manually instead of using ThreadPool.QueueUserWorkItem.

Categories

Resources