473,573 Members | 2,806 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Confused about using Invoke in worker threads. - C#

63 New Member
So why is it that we need to use the Invoke method when updating the GUI?

The following is the way we are suppose to update GUI components:

Expand|Select|Wrap|Line Numbers
  1. delegate void textIt(object o);
  2. public partial class Form1 : Form
  3. {
  4.         public Form1()
  5.         {
  6.             InitializeComponent();
  7.         }
  8.         private void Form1_Load(object sender, EventArgs e)
  9.         {
  10.             //Main Thread
  11.             Label l = new System.Windows.Forms.Label();
  12.             this.Controls.Add(l);
  13.  
  14.             System.Threading.Thread testThread = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(testStart));
  15.             testThread.Start(l);
  16.  
  17.         }
  18.         private void testStart(object o)
  19.         {
  20.             //testThread
  21.             if (((Label)o).InvokeRequired)
  22.             {
  23.                 textIt t = new textIt(testStart);
  24.                 this.Invoke(t, o);
  25.             }
  26.             else
  27.             {
  28.                 ((Label)o).Text = "TEST";
  29.             }
  30.        }
  31. }
  32.  

If I delete the delegate and change the method testStart(objec t o) to:

Expand|Select|Wrap|Line Numbers
  1. private void testStart(object o)
  2. {
  3.        ((Label)o).Text = "TEST";
  4. }
  5.  
I don't get any problems. In fact, I have yet to have a problem with X number of threads changing the GUI directly as long as I implement mutual exclusion correctly.

I have read that the properties cannot be changed by any thread other then the one that created it. Is that a suggestion or a fact? If it is a suggestion, then what could go wrong? If it is a fact then how is it that I have been accessing the properties directly from different threads? does the compiler rewrite the code so that it does call Invoke?
May 21 '08 #1
5 1675
iLL
63 New Member
Sorry for this but... Bump
May 21 '08 #2
Plater
7,872 Recognized Expert Expert
It's not that they "CANNOT" it's that they "SHOULD NOT"
You will only ever see an exception when in debug mode.
What it could cause is messages coming in mixed up with each other because one thread tries to access the gui object while another one is in the middle of it.

Expand|Select|Wrap|Line Numbers
  1. private delegate void ChangeTextCallback(string msg);
  2.  
  3. private void SetLabelText(string msg)
  4. {
  5.     if (this.InvokeRequired)
  6.     {
  7.         ChangeTextCallback d = new ChangeTextCallback(SetLabelText);
  8.         this.Invoke(d, msg);
  9.     }
  10.     else
  11.     {
  12.         myLabel1.Text = msg;
  13.     }
  14. }
  15.  
May 21 '08 #3
iLL
63 New Member
I'm still a little confused

If I implement mutual exclusion properly, then do I still need to worry about implementing it this way?

And if I do use this method, do I still need to use locks? And if not, what if two different threads call Invoke at the same time, how does that work? Does some sort of stack keep track of waiting Invoke calls?
May 21 '08 #4
Plater
7,872 Recognized Expert Expert
If I understand correctly, invoke sends out a special windows message on the message pump with the applicable data as a payload.
So if multiple threads call invoke, multiple messages will be sent out, but processed one at a time?
May 21 '08 #5
iLL
63 New Member
Thanks ;)

............... ..
May 21 '08 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

0
293
by: arno | last post by:
Hi, I use an asynchronous call to execute a method in a windows service : TargetSystemDelegate TargetSystemdelegate = new TargetSystemDelegate(TargetSystem .Invoke ); AsyncCallback cb = new AsyncCallback(TargetSytemCallback ); IAsyncResult ar = TargetSystemdelegate .BeginInvoke(ref activity , cb, null);
3
14095
by: Koji Ishii | last post by:
I have a worker thread, and the thread needs to listen to WinForms Control's SizeChanged event. Here's my code. Control c = ...; if (c.InvokeRequired) { c.BeginInvoke(===don't know how to write here===); } else { c.SizeChanged += new EventHandler(this.OnOwnerSizeChanged); }
11
3772
by: Doug Thews | last post by:
I've been working on some samples that use BeginInvoke/EndInvoke. In one example, I call BeginInvoke and pass it an AsyncCallback function pointer. I was messing around with ReaderWriterLocks and noticed that if I did this, it worked (please ignore the lack of try ... catch blocks, because I cut down the code to be more brief - I have a...
5
4654
by: User N | last post by:
I have a log class with static methods that grab and release a mutex as required. The log class is designed to be called from both GUI and thread pool threads, and dump output to a logfile and a RichEditBox. To give you some idea of the approach I took... private static RichTextBox rtb; private delegate void RtbAppendTextHandler(string...
6
31861
by: Peter Rilling | last post by:
Okay, I have the main thread which does all the work. This main thread spawns a worker thread that just periodically poles the environment looking for a certain condition. This second thread is very small, and only is responsible for raising a flag when the environment changes. What I want is for the main thread to raise an event when the...
4
3562
by: Charles Law | last post by:
Hi guys. I have two threads: a main thread and a background thread. Lots of stuff happens in the background thread that means I have to update several (lots) of controls on a form. It is quite tiresome to have to write code to call MyControl.Invoke for each control on the form, along with the delegates that are required for each. Is...
4
1573
by: Brad Coble | last post by:
I have an activex control that is used in an old app originally written in VB6. It works good. I updated the VB6 app to VB.net. Got it working, sort of. The activex control uses withevents and fires an event when there is incoming message traffic. I need to capture that data. The event fires sometimes. I know it should be firing more often...
2
3534
by: Amit Dedhia | last post by:
Hi I am developing a scientific application which has moderate level image processing involved. In my application, there is a main application form which invokes another form. When this form is running, a timer function keeps executing every 250ms. The timer function does some real time data processing and generates a bitmap which needs...
0
1277
by: mike1reynolds | last post by:
In a background worker threads are MTA, while UI threads must be STA. Attempting to instantiate a form class in a background worker throws an exception, so invocation of a delegate is required. My problem is that I have encapsulated all of my twain driver code into a plain class with no form which I instantiate in the background worker. If the...
0
7760
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7996
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8191
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7760
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6392
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5573
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5284
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3724
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3723
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.