473,785 Members | 2,327 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 1718
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
14107
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
3788
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 try...catch surround the AcquireWriterLock method): ---------- myLock.AcquireWriterLock(1000);...
5
4668
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 output); private static RtbAppendTextHandler RtbAppendText; Log.Init(RichTextBox richTextBox,...
6
31868
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 change has been flagged. I other words, I want the main thread to raise the event, not this small...
4
3584
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 there a better way to do this? What I mean is, if I could marshal the
4
1586
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 because i run the vb6 app and watch the traffic. When I look at the debuger output I see a lot...
2
3566
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 to be displayed on a picture control. This is done using this->Invoke(...) in the form.
0
1295
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 scanner is not loaded I need to display a simple dialog, so I created a delegate on the main form,...
0
9647
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9491
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10357
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10163
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10104
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
8988
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6744
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5397
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3668
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.