473,626 Members | 3,467 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Correct way to call a Delegate?

G'day,

I think I got my head around using delegates, particularily when
updating the user interface from another thread. I got it all sussed,
just not 100% sure on the correct syntax for calling the delegate.

Is
this.Invoke(del UpdateUI, args);
Same as
delUpdateUI(i);

The following code is a win form. I press button and it starts a new
worker thread that counts from 1 to 20,000 and updates a label as it
goes.

Can someone tell which of the two methods calc() or calc2() has the
correct way of calling the delUpdateUI() delegate?

Do both delegate calls get marshalled to the UI thread, just different
way of expressing the same thing? Both work just fine, so which is the
correct way?

Cheers,
PeterZ
------------------------------------------------------
private void btnStartCount_C lick(object sender, System.EventArg s e)
{
// Run the calculation on a sperate worker thread.
lblCounter.Text = "";
Thread workerThread = new Thread(new ThreadStart(wor kerSub));
workerThread.St art();
}

private void workerSub()
{
// "calc" and "calc2" do the same thing, just different way of
// calling the delUpdateUI() delegate. Which is the correct of
// the two?

//calc(20000));
calc2(20000);
MessageBox.Show ("I'm finished!");
}

public void calc(int countTo)
{
int i;

// Instantiate the delegate reponsible for updating the UI.
DelUpdateUI delUpdateUI = new DelUpdateUI(upd ateUI);

for (i=1; i <=countTo; i++)
{
// The caller is on a different thread to the UI, must
// update the label through delegate.
object[] args = new object[] {i};
this.Invoke(del UpdateUI, args);
}
}

public void calc2(int countTo)
{
int i;

// Instantiate the delegate reponsible for updating the UI.
DelUpdateUI delUpdateUI = new DelUpdateUI(upd ateUI);

for (i=1; i <=countTo; i++)
{
// The caller is on a different thread to the UI, must
// update the label through delegate.
delUpdateUI(i);
}
}

public delegate void DelUpdateUI(int count);
private void updateUI(int count)
{
// Update the user interface.
lblCounter.Text = count.ToString( );
}

------------------------------------------------------

Nov 17 '05 #1
4 1864
OK... I'm going out on a limb here. See if I get clobbered for it. :-)

The correct way to call back into the UI thread is by using Invoke().
The difference between doing this and calling the delegate directly are
as follows.

If you call the delegate directly, the delegate's method code will run
under the control of the calling thread. This means (in your case) that
the label in the UI will be updated under the control of your worker
thread, which is a no-no. Only the UI thread should update UI controls.

Using Invoke causes the delegate's method code to run under the control
of the main (UI) thread.

Nov 17 '05 #2
<pz****@hotmail .com> wrote:
I think I got my head around using delegates, particularily when
updating the user interface from another thread. I got it all sussed,
just not 100% sure on the correct syntax for calling the delegate.

Is
this.Invoke(del UpdateUI, args);
Same as
delUpdateUI(i);


No.

delUpdateUI.Inv oke(args)

is the same as

delUpdateUI(i).

When you call Invoke on a Control, that makes sure that the delegate is
called on the UI thread. A straight delegate call doesn't.

calc() has it correctly; calc2() doesn't.

Note that you might want to use BeginInvoke - you don't really need to
wait for the UI to be updated before you proceed, do you? Having said
which, chances are you'll only see 20,000 if you call BeginInvoke,
because it'll all happen *very* quickly.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #3
Bruce Wood <br*******@cana da.com> wrote:
OK... I'm going out on a limb here. See if I get clobbered for it. :-)

The correct way to call back into the UI thread is by using Invoke().
The difference between doing this and calling the delegate directly are
as follows.

If you call the delegate directly, the delegate's method code will run
under the control of the calling thread. This means (in your case) that
the label in the UI will be updated under the control of your worker
thread, which is a no-no. Only the UI thread should update UI controls.

Using Invoke causes the delegate's method code to run under the control
of the main (UI) thread.


No need for clobbering at all - that's exactly correct. (Some would
argue that a better way of calling into the UI thread is to use
BeginInvoke, but it depends on the situation.)

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #4
Thanks Bruce and Jon - exactly the respnses I was looking for!

I can now safely tackle the weird world of multithreading!
:-)

Cheers,
PeterZ

Nov 17 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
4674
by: Ben Reese | last post by:
Simplified. I have 2 forms running on seperate threads (and message queues) I am having some odd problems with with the form on the second Thread/message queue freezing and/or dyinig, seemingly at random. I have been carfull always to call Form2.Invoke(someDelegate) Whenever I want to access a method on the second form from the first. I have tracked down 1 remaining occurence Where from 1 wants to disable a button on form 2
3
11873
by: David N | last post by:
Hi All, I just wonder if in C#, I can develop a user defined control that can call its parent function which is not yet developed. For example, how do I make my user control call a to-be-developed-function cmdOkay_Click() function as described below. 1. Create an user control that contains an OK button as below Public Class MyButton:System.Windows.Form.UserControl
23
2467
by: jm | last post by:
This works, but I don't know why. static void Main() { // Queue the task. ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc),new Form1()); Application.Run(); }
2
3003
by: rawCoder | last post by:
Hi I am having this InvalidOperationException with message Cannot call Invoke or InvokeAsync on a control until the window handle has been created This is raised when i try to invoke a method with arguments I need to do this as the method is being called Asynchronously from elsewhere using delegate's BeginInvoke method. The form is well created/initialized yet the messages states otherwise.
2
5359
by: Gerda | last post by:
Hi! I've implemented many times an asynchronous call of a method with a call backfunction successfully. But to implement this with VB.NET is not so successfully. I can implement all events ProcessingEvent, CompletedEvent, etc. It works fine and copies all files in the background ... Bit to make it perfekt I want to implement a callback function wich will be
1
1375
by: ryan1234 | last post by:
My ultimate goal is to get something like "ping.exe" to re-direct it's standardOutput in real time to an .aspx page. I've been able to get this behavior to work just fine in a regular console application. I execute the process and the output is re- directed to a windows textbox. Below is the code I'm using to do that: Private Sub Button1_Click(ByVal sender As System.Object, ByVal e
6
5115
by: HolyShea | last post by:
All, Not sure if this is possible or not - I've created a class which performs an asynchronous operation and provides notification when the operation is complete. I'd like the notification to be performed on the same thread thread that instantiated the class. One way to do this is to pass an ISynchronizeInvoke into the class and use it to synchronize the callback. In the constructor of the class, could I take note of the current thread...
5
2137
by: RP | last post by:
I have a function to fill combo box items. I pass SQL query and combo box name as arguments. This function is located in another class. In my Form, I have declared a delegate to this function before the namespace as; public delegate void dFillItems(ObjectName as string, Query as string) On my Forms I have several combo boxes and get filled when they get focus. Is it proper to use delegate in this situation? Will it improve...
1
1685
by: =?Utf-8?B?RGF2ZQ==?= | last post by:
I have a class that Form1 calls to do some work. I would like to report back progress from the class to a richtextbox, will call it m_report, on the form. Like in the class, Form1.m_report.Text= "Calculating variable 10"; How would I do that.
0
8202
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
8707
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
8641
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
8366
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
8510
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6125
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5575
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
4093
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...
1
1812
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.