473,378 Members | 1,354 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,378 software developers and data experts.

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(delUpdateUI, 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_Click(object sender, System.EventArgs e)
{
// Run the calculation on a sperate worker thread.
lblCounter.Text = "";
Thread workerThread = new Thread(new ThreadStart(workerSub));
workerThread.Start();
}

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(updateUI);

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(delUpdateUI, args);
}
}

public void calc2(int countTo)
{
int i;

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

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 1841
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(delUpdateUI, args);
Same as
delUpdateUI(i);


No.

delUpdateUI.Invoke(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.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #3
Bruce Wood <br*******@canada.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.com>
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
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...
3
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...
23
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
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...
2
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...
1
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...
6
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...
5
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...
1
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=...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.