Posts

Showing posts with the label multithreaded

Cross thread UI calls in C#

Image
If you try to call UI functions through threads other than the one the created the UI elements then an error will occur. To avoid those type of errors we need to have thread-safe calls to the corresponding Windows controls. For example, to make a thread-safe call for a textbox control, the following is valid: private void SetText(string text) { if (txtCommand.InvokeRequired) this.Invoke(new Action<string>(SetText), text); else txtCommand.Text = text; } The Invoke function will be called if the function is called from a thread other than the one that created the control. Here is a second example that will take two arguments; the first one is the control itself. private void EnableButton(Button button, bool enabled) { // InvokeRequired compares the thread ID of the // calling thread to the thread ID of the creating thread. // If these threads are different, it returns true. if (button.InvokeRequired) button.Invoke(new Action<Button...

Hook to a BackgroundWorker (C#)

Image
Using the BackgroundWorker class (that resides in the System.ComponentModel namespace) is very convenient to use for parallel processing. In the following example I add a BackgroundWorker to split the work done in several experiment objects. For that, I use an AddWorker function that creates a thread for each experiment. The line that "sticks" the application execution flow until all threads are completed, is the last one: System.Threading.AutoResetEvent waitHandle; public void Calculate() { //initialize the list of threads (BackgroundWorkers) workers = new List<BackgroundWorker>(); //initialize the object that will wait during the execution process waitHandle = new System.Threading.AutoResetEvent(false); //add a thread for each experiment object foreach (Experiment experiment in Experiments) AddWorker(experiment); //stick here until we use waitHandle.Set() waitHandle.WaitOne(); } The AddWorker() adds a thread for each experiment ...