473,770 Members | 1,468 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Anonymous Delegate

hi @all,

is there something like an anonymous delegate?

This is the original code:

--
private delegate void DelegateSetForm Caption(string text);
private void SetFormCaption( string text)
{
if (this.InvokeReq uired)
{
DelegateSetForm Caption d = new
DelegateSetForm Caption(SetForm Caption);
this.Invoke(d, new object[] { text });
}
else { this.Text = text; }
}
--

I'd like to avoid the delegate declaration, e.g.:

--
private void SetFormCaption( string text)
{
if (this.InvokeReq uired)
{
this.Invoke(
new delegate(string text)(SetFormCa ption), new object[] { text }
);
}
else { this.Text = text; }
}
--

Is this possible?
mfG
--stefan <--
Aug 28 '08 #1
7 2725
Stefan Hoffmann wrote:
private void SetFormCaption( string text)
{
if (this.InvokeReq uired)
{
this.Invoke(
new delegate(string text)(SetFormCa ption), new object[] { text }
);
}
else { this.Text = text; }
}
If you're using C# 3.0:

this.Invoke((Ac tion) () =this.Text = text);

Action delegate type is in the System namespace in System.Core assembly.

If you're using C# 2.0:

delegate void Action(); // a single delegate type will do for all
// ...
this.Invoke((Ac tion) delegate { this.Text = text; });

The reference to 'text' in the C# 3.0 syntax (lambda syntax) and in the
C# 2.0 anonymous delegate syntax is ok, because the parameter will be
captured and thus made available to the delegate when the control
invokes it on the UI thread.

-- Barry

--
http://barrkel.blogspot.com/
Aug 28 '08 #2
hi Barry,

thanks for your answer.
mfG
--stefan <--
Aug 28 '08 #3
If you're using C# 2.0:
>
delegate void Action(); // a single delegate type will do for all
// ...
this.Invoke((Ac tion) delegate { this.Text = text; });
Use MethodInvoker instead of defining your own. The CLR recognizes
MethodInvoker and executes a specialized fast-path implementation of Invoke.
Aug 28 '08 #4
On Thu, 28 Aug 2008 12:52:47 -0700, Ben Voigt [C++ MVP]
<rb*@nospam.nos pamwrote:
>If you're using C# 2.0:

delegate void Action(); // a single delegate type will do for all
// ...
this.Invoke((Ac tion) delegate { this.Text = text; });

Use MethodInvoker instead of defining your own. The CLR recognizes
MethodInvoker and executes a specialized fast-path implementation of
Invoke.
Can you elaborate? I can see in Reflector that the framework (the Control
class, not the CLR) special-cases delegates of type EventHandler,
MethodInvoker, and WaitCallback. For those types, it casts directly
rather than calling Delegate.Dynami cInvoke().

But do most people really care? Just what kind of performance difference
are we talking about here? Especially given all the other overhead
involved in calling Invoke() (after all, for the true cross-thread case it
involves a full context switch, which is surely at least as costly as any
of the extra work in DynamicInvoke() ?).

Seems like a premature optimization to me. Is there some specific reason
to believe otherwise (especially given that the framework-defined Action
delegate type could be considered more expressive)?

Pete
Aug 28 '08 #5


"Peter Duniho" <Np*********@nn owslpianmk.comw rote in message
news:op******** *******@petes-computer.local. ..
On Thu, 28 Aug 2008 12:52:47 -0700, Ben Voigt [C++ MVP]
<rb*@nospam.nos pamwrote:
>>If you're using C# 2.0:

delegate void Action(); // a single delegate type will do for all
// ...
this.Invoke((Ac tion) delegate { this.Text = text; });

Use MethodInvoker instead of defining your own. The CLR recognizes
MethodInvoke r and executes a specialized fast-path implementation of
Invoke.

Can you elaborate? I can see in Reflector that the framework (the Control
class, not the CLR) special-cases delegates of type EventHandler,
Ok, didn't check whether that was MSIL or internalcall. Doesn't much
matter, does it?
MethodInvoker, and WaitCallback. For those types, it casts directly
rather than calling Delegate.Dynami cInvoke().

But do most people really care? Just what kind of performance difference
are we talking about here? Especially given all the other overhead
involved in calling Invoke() (after all, for the true cross-thread case it
involves a full context switch, which is surely at least as costly as any
of the extra work in DynamicInvoke() ?).
Posting a message to another thread waits for the next context switch, it
doesn't insert an extra context switch.

Plus, DynamicInvoke is a very expensive operation.
>
Seems like a premature optimization to me. Is there some specific reason
to believe otherwise (especially given that the framework-defined Action
delegate type could be considered more expressive)?
The documentation (http://msdn.microsoft.com/en-us/library/zyzhdc6b.aspx)
says:
The delegate can be an instance of EventHandler, in which case the sender
parameter will contain this control, and the event parameter will contain
EventArgs..::.E mpty. The delegate can also be an instance of MethodInvoker,
or any other delegate that takes a void parameter list. A call to an
EventHandler or MethodInvoker delegate will be faster than a call to another
type of delegate.

Also "premature optimization" assumes that there's a cost to the
optimization. Here, there's effectively no cost at all.

>
Pete
Aug 28 '08 #6
On Thu, 28 Aug 2008 16:08:09 -0700, Ben Voigt [C++ MVP]
<rb*@nospam.nos pamwrote:
Ok, didn't check whether that was MSIL or internalcall. Doesn't much
matter, does it?
No, not really. I just like being precise.
Posting a message to another thread waits for the next context switch,
it doesn't insert an extra context switch.
I suppose that depends on how you look at it. Calling Invoke() blocks the
calling thread, which will prematurely relinquish the current timeslice.
If you've got a CPU bound thread, with the usual 50ms timeslice, but it's
calling Invoke() every 5ms, I'd say that's adding 9 context switches for
every context switch that would have happened otherwise.

I'll acknowledge that you may have some other way of looking at it in
which you come to a different conclusion. But by my reckoning, Invoke()
does in fact wind up forcing a context switch that wouldn't otherwise
happen.

Maybe you're thinking of BeginInvoke() instead? I'd agree that that
method doesn't add context switches to the execution of the code.
Plus, DynamicInvoke is a very expensive operation.
The whole process of invoking is a very expensive operation. That
DynamicInvoke is "very expensive" isn't necessarily important.

In particular, by my measurements it doesn't look like it's expensive
enough to cause a significant difference in performance. I ran a little
test, calling Invoke() 100,000 times in a row with a do-nothing method,
once with a type of MethodInvoker and once with a type of Action.

The timing was more sensitive to which test ran first than to the actual
type. That is, the first test always was slower, regardless of which type
was being used for the call. Changing the test so that it did a "warm-up"
first, I found more consistent results showing that 100,000 calls took
about 3.3 seconds for MethodInvoker and 4.2 seconds for Action.

If I changed the test so that the method actually did something useful --
for example, setting the Text property of a control to the formatted value
of my loop index -- the execution time dropped precipitously. Almost 40
seconds in either case, a 10x slowdown.

So, yes it's faster to call MethodInvoker, but putting that into context
it means you really don't want to be calling Invoke() _either_ way too
often, assuming the delegate is actually doing to be doing something
interesting, and in any case the overhead of the call is very tiny as
compared to the cost of whatever code might actually be executed by the
delegate (10% at the most).
The documentation
(http://msdn.microsoft.com/en-us/library/zyzhdc6b.aspx) says:
The delegate can be an instance of EventHandler, in which case the
sender parameter will contain this control, and the event parameter will
contain EventArgs..::.E mpty. The delegate can also be an instance of
MethodInvoker, or any other delegate that takes a void parameter list. A
call to an EventHandler or MethodInvoker delegate will be faster than a
call to another type of delegate.
Well, I can't say the documentation is wrong. My own tests prove it
correct. But that's only because the docs don't quantify how much
faster. I wouldn't call the difference significant.
Also "premature optimization" assumes that there's a cost to the
optimization. Here, there's effectively no cost at all.
Eye of the beholder. Personally, I find the newer generic delegate types
more expressive. But sure...if you don't personally see any difference
between "MethodInvo ker" and "Action" semantically, the only cost involved
is that of remembering which is faster and of typing the extra
characters. Obviously neither costs is significant.

However, I still find it misleading to imply that the optimization is
worth doing. I saw no practical difference in performance, even if there
was a tiny measurable difference. No real world application is going to
find it matters which delegate type you use.

Pete
Aug 29 '08 #7
Ben Voigt [C++ MVP] wrote:
Also "premature optimization" assumes that there's a cost to the
optimization. Here, there's effectively no cost at all.
Knowing a piece of trivia is a cost :)

-- Barry

--
http://barrkel.blogspot.com/
Aug 29 '08 #8

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

Similar topics

0
1654
by: Cordell Lawrence | last post by:
Okay guys, We are wondering if this is a bug in Framework 2.0.40607 and looking for some clarification on the issue. Take a look at the folowing code. public delegate bool BoundryTest(int myVal);
3
8800
by: anonymous | last post by:
I believe I ran into an interesting way to create memory leaks in C# 2.0 using anymous delegates. Here is a sample of the code in question. private void Handle_Event(object sender, EventArgs e) { Timer timer = new Timer(); timer.Interval = 10000; NotifyForm notifyForm = new notifyForm(); notifyForm.Show(); timer.Tick += delegate(object timerSender, EventArgs tArgs)
5
1694
by: cody | last post by:
I have a very funny/strange effect here. if I let the delegate do "return prop.GetGetMethod().Invoke(info.AudioHeader, null);" then I get wrong results, that is, a wrong method is called and I have no clue why. But if I store the MethodInfo in a local variable I works as expected. I do not understand why this is so, shouldn't both ways be semantically equal?
4
4944
by: Harold Howe | last post by:
I am running into a situation where the compiler complains that it cannot infer the type parameters of a generic method when one of the function arguments is an anonymous method. Here is a complete code example: //----------------------------- using System; using System.Collections.Generic;
7
3794
by: Bill Woodruff | last post by:
I've found it's no problem to insert instances of named delegates as values into a generic dictionary of the form : private Dictionary<KeyType, DelegatemyDictionary = new Dictionary<KeyType, Delegate); using the standard .Add method of the Dictionary, passing in the name of the delegate instance for the value. private void myMethodBody()
3
1775
by: William Stacey [C# MVP] | last post by:
It would be handy to be able to ref "this" from inside an AM such as: (string s) { Console.Writeline(s); DoSomething(this); } So treating am like a method of a class (which it is). Currently we have no context to know so you have to pass that as state which seems kinda
15
4850
by: Matt | last post by:
Hi There, Can anyone explain me the real advantages of (other than syntax) lambda expressions over anonymous delegates? advantage for one over the other. delegate int F(int a); F fLambda = a =a++; F fAnonymous = delegate(int a) { return a++; }; fLambda(1);
4
2394
by: Frankie | last post by:
I have just gotten up to speed on what anonymous methods are (syntax, capabilities, etc), and how they can be used with /called via delegates. What I am wondering is... 1. Are they only/mostly syntactic sugar (important as that can be)? 2. Are anonymous methods *required* anywhere? That is, are anonymous methods the only way to accomplish certain tasks in ..NET programming?
3
1879
by: Robert Howells | last post by:
Is there any such thing as an "anonymous delegate"? I understand what an anonymous method is, but I'm unclear of the concept of anonymous delegate (if it is even a valid term to be using). Is an "anoymous delegate" simply an anonymous method used in conjunction with a delegate declaration? Thanks!
0
1422
by: Peter Duniho | last post by:
On Mon, 01 Sep 2008 16:14:10 -0700, Blip <blip@krumpli.comwrote: Briefly, an anonymous method is exactly that: a method without a name. When you use the "delegate" keyword to declare an anonymous method, all you're doing is writing a method the same as you would anywhere else, except that it doesn't have a name, and so you have to use it right away rather than being able to refer to it elsewhere. (And I mean that only in the static,...
0
9592
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
10059
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
10005
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,...
1
7416
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
6679
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
5313
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...
0
5452
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3576
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2817
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.