473,799 Members | 3,033 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

delegate confusion

hello world.

i would like to implement a class with a timer, witch informs me every
second about it's tick. the code works already, but i would like to
change a thing (or more).

<code>
//at the moment i initialize the object with the constructor:
public myClass(System. Timers.ElapsedE ventHandler CallMeBack)
{
System.Timers.T imer myTimer = new System.Timers.T imer(1000);
myTimer.Elapsed += CallMeBack;
myTimer.Enabled = True;
}

//the call from outside (other class) looks like:
myClass myObject = new myClasst(new
System.Timers.E lapsedEventHand ler(this.Answer ingMachine));

//with...
private void AnsweringMachin e(object sender,
System.Timers.E lapsedEventArgs e)
{
//THAT'S WHAT I WOULD LIKE TO DO:
//someString = ((myClass)sende r).getValue();
}
</code>

now to my problem (i commented it already in the code):
sender returns the timer and elapsedeventarg s returns the time. i need
access to the calling myObject and it would be very neat to change the
sender and/or the arguments. is there a good solution? i've tried to
inherit from timer but failed, because delegates and events are really
virgin soil for me, so i get confused ` ` o¿o ´ ´

i nearly forgot: i used this implementation, because the polling from
myClass would work completly independent. but would it be wiser to set
a timer in the "outer space" instead of "myClass"?

talked enough.

thanks for putting on the thinking caps...
rené

Jul 26 '07 #1
11 1833
"ohmmega" <sh****@gmx.atw rote in message
news:11******** **************@ k79g2000hse.goo glegroups.com.. .
now to my problem (i commented it already in the code):
sender returns the timer and elapsedeventarg s returns the time. i need
access to the calling myObject and it would be very neat to change the
sender and/or the arguments. is there a good solution?
One way to do it is to redirect the timer callback into your own routine,
and this routine can in turn call the original callback with the arguments
of your choice, such as "this" for the "sender":
class myClass
{
private System.Timers.E lapsedEventHand ler theCallBack;

public myClass(System. Timers.ElapsedE ventHandler CallMeBack)
{
this.theCallBac k = CallMeBack;
System.Timers.T imer myTimer = new System.Timers.T imer(1000);
myTimer.Elapsed += MyCallback;
myTimer.Enabled = True;
}

private void MyCallback(obje ct sender,
System.Timers.E lapsedEventArgs e)
{
theCallBack(thi s, e);
}

//(Here goes the rest of class, such as clean-up code for the Timer)
}
Jul 26 '07 #2
ohmmega,

I don't have a compiler on me but I think something along the lines of
this should do what you want. Our anonymous method will handle the
event, and then fire the event handler with myClass as the sender
instead of myTimer.

public myClass(System. Timers.ElapsedE ventHandler CallMeBack)
{
System.Timers.T imer myTimer = new System.Timers.T imer(1000);
myTimer.Elapsed += delegate(object sender,
System.Timers.E lapsedEventArgs e)
{
CallMeBack.Invo ke(this, e);
};
myTimer.Enabled = True;
}

BTW: You need to make myTimer a member variable or it will get garbage
collected.

Good Luck,
James

Jul 26 '07 #3
On Thu, 26 Jul 2007 07:40:19 -0700, ohmmega <sh****@gmx.atw rote:
now to my problem (i commented it already in the code):
sender returns the timer and elapsedeventarg s returns the time. i need
access to the calling myObject and it would be very neat to change the
sender and/or the arguments. is there a good solution? i've tried to
inherit from timer but failed, because delegates and events are really
virgin soil for me, so i get confused ` ` o¿o ´ ´
Alberto has posted one good solution. In his method, the class
initializing the timer essentially makes it look as though it is the class
implementing the timer. It encapsulates the timer itself internally; in
addition to the obvious advantage of addressing your question, it also has
the advantage that the myClass class can change the implementation of the
timer more easily (and even more easily if you change the handler delegate
type to something that myClass defines rather than using the one in the
Timers namespace :) ).

There are at least two other ways I can think of to address the issue,
which may or may not be appropriate for your needs depending on how you
want it to work.

The first involves simply saving the myClass instance reference and using
that. For example:

public ClientClass
{
myClass myObject;

void SomeMethod()
{
myObject = new myClass(Answeri ngMachine);
}

void AnsweringMachin e(object sender, ElapsedEventArg s e)
{
someString = myObject.getVal ue();
}
}

Because the delegate includes a reference to the class instance used to
create the delegate, you can then refer to instance members, such as the
"myObject" field, from within the delegate method.

A variation on the above would be to create a simple class in which you
put the delegate method, and which stores the "myObject" instance. That
way you could create a new instance for each instance of myClass that you
create, if that was desirable for some reason. Of course, you would have
to include in that simple class some way to get back to the ClientClass if
you wanted to be able to do things specific to that instance from within
the callback as well. As you can see, this technique can get arbitrarily
complicated if you want. :)

Another way to address the issue would be to use an anonymous delegate:

public ClientClass
{
void SomeMethod()
{
myClass myObject;
ElapsedEventArg s callback = delegate(object sender,
ElapsedEventArg s e)
{ someString = myObject.getVal ue(); }

myObject = new myClass(callbac k);
}
}

This takes advantage of the fact that the local variable "myObject" is
"captured" by the anonymous delegate. So you can use the variable within
the code of the delegate, and it will retain the value you set it to in
the SomeMethod() method. This might be especially appropriate if the
callback method exists for the sole purpose of handling that one
situation, which is in fact often the case for this sort of thing.
i nearly forgot: i used this implementation, because the polling from
myClass would work completly independent. but would it be wiser to set
a timer in the "outer space" instead of "myClass"?
I don't think it matters. If you have no need to access the timer from
outside myClass, I would say that you should not store it outside
myClass. If the myClass instance itself has no need to access the timer
either, then I would say there's no need to store it even within myClass.

Pete
Jul 26 '07 #4
On Thu, 26 Jul 2007 10:05:37 -0700, james <ja********@gma il.comwrote:
public myClass(System. Timers.ElapsedE ventHandler CallMeBack)
{
System.Timers.T imer myTimer = new System.Timers.T imer(1000);
myTimer.Elapsed += delegate(object sender,
System.Timers.E lapsedEventArgs e)
{
CallMeBack.Invo ke(this, e);
};
myTimer.Enabled = True;
}
Any particular reason you prefer the "CallMeBack.Inv oke(this, e)" syntax
as opposed to the (IMHO more readable) "CallMeBack(thi s, e)" syntax? I
believe that in situations where you know the delegate type exactly (as is
the case here), the latter is preferable and somewhat more efficient at
run-time.
BTW: You need to make myTimer a member variable or it will get garbage
collected.
Not true. This code works fine:

static void Start()
{
Timer timer = new Timer();

timer.Elapsed += ElapsedHandler;
timer.Interval = 2000;
timer.Start();
}

static void ElapsedHandler( object sender, ElapsedEventArg s e)
{
Console.WriteLi ne("timer elapsed");
}

static void Main(string[] args)
{
Start();

GC.Collect();
Console.ReadLin e();
}

Pete
Jul 26 '07 #5
Peter Duniho <Np*********@nn owslpianmk.comw rote:
On Thu, 26 Jul 2007 10:05:37 -0700, james <ja********@gma il.comwrote:
public myClass(System. Timers.ElapsedE ventHandler CallMeBack)
{
System.Timers.T imer myTimer = new System.Timers.T imer(1000);
myTimer.Elapsed += delegate(object sender,
System.Timers.E lapsedEventArgs e)
{
CallMeBack.Invo ke(this, e);
};
myTimer.Enabled = True;
}

Any particular reason you prefer the "CallMeBack.Inv oke(this, e)" syntax
as opposed to the (IMHO more readable) "CallMeBack(thi s, e)" syntax? I
believe that in situations where you know the delegate type exactly (as is
the case here), the latter is preferable and somewhat more efficient at
run-time.
It's perhaps preferable from a readability point of view, but the
compiled code is the same. The syntax you're suggesting is just sugar
provided by the C# compiler.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Jul 26 '07 #6
On Thu, 26 Jul 2007 11:34:34 -0700, Jon Skeet [C# MVP] <sk***@pobox.co m>
wrote:
It's perhaps preferable from a readability point of view, but the
compiled code is the same. The syntax you're suggesting is just sugar
provided by the C# compiler.
Okay. I read an article that suggested that because Invoke can be used
without knowing the exact delegate signature, some extra run-time stuff
has to happen to handle that syntax. But maybe that referred to a
different way of using the Invoke() method. Or maybe it was just plain
wrong. :)
Jul 26 '07 #7
Hey Pete,

I tried your code and System.Timers.T imer isn't garbage collected, but
a System.Threadin g.Timer is garbage collected. Any idea what is going
on here?
static void Start()
{
System.Threadin g.Timer threadingTimer = new
System.Threadin g.Timer(delegat e
{
Console.WriteLi ne("System.Thre ading.Timer");
}, null, 0, 2000);

System.Timers.T imer timersTimer = new
System.Timers.T imer();

timersTimer.Ela psed += delegate
{
Console.WriteLi ne("System.Time rs.Timer");
};
timersTimer.Int erval = 2000;
timersTimer.Sta rt();
}
static void Main(string[] args)
{
Start();

GC.Collect();
Console.ReadLin e();
}

Thanks,
James

Jul 26 '07 #8
Peter Duniho <Np*********@nn owslpianmk.comw rote:
It's perhaps preferable from a readability point of view, but the
compiled code is the same. The syntax you're suggesting is just sugar
provided by the C# compiler.

Okay. I read an article that suggested that because Invoke can be used
without knowing the exact delegate signature, some extra run-time stuff
has to happen to handle that syntax. But maybe that referred to a
different way of using the Invoke() method. Or maybe it was just plain
wrong. :)
I think that was probably a different Invoke - like Control.Invoke,
etc. Or possibly it was Delegate.Dynami cInvoke.

The Invoke method for an individual delegate type is declared by the
delegate itself, with appropriate parameters - which is why it isn't in
the Delegate class.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Jul 26 '07 #9
On Thu, 26 Jul 2007 12:43:29 -0700, Jon Skeet [C# MVP] <sk***@pobox.co m>
wrote:
I think that was probably a different Invoke - like Control.Invoke,
etc. Or possibly it was Delegate.Dynami cInvoke.
Here's the article:
http://forums.microsoft.com/msdn/Sho...66938&SiteID=1

The reply was from a "moderator MVP", and it appears to me that the
messages are specifically about Invoke on a delegate instance. But I may
have misunderstood.
The Invoke method for an individual delegate type is declared by the
delegate itself, with appropriate parameters - which is why it isn't in
the Delegate class.
Makes sense to me. Obviously, that should be exactly the same as just
calling the delegate as a method.

Pete
Jul 26 '07 #10

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

Similar topics

9
1479
by: Wiktor Zychla | last post by:
Hello, I wonder why the delegate declaration needs named parameters? public delegate void MyDelegate( int a, int b ); // ok public delegate void MyDelegate( int, int ); // compiler error C allows to define both: typedef void (*MyDelegate)(int); // ok
8
4545
by: Phill | last post by:
All the event handlers seem to pass an Object and an EventArgs object. If the event doesn't need this info why pass them anyway? It is inefficient.
3
2619
by: Minh Khoa | last post by:
Please give me more information about delegate and its usage? Why do i use it and when?
7
1779
by: Ant | last post by:
Hello, Very simple question but one I need clarified. Which part of the statement below is considered the 'delegate'? Is it the 'new System.EventHandler' or the btnAccept_Click? or is it the piece of code which doesn't appear here, but abstracts the btnAccept_Click method?
1
1825
by: Quimbly | last post by:
I'm having some problems comparing delegates. In all sample projects I create, I can't get the problem to occur, but there is definitely a problem with my production code. I can't give all the code, as there's simply too much, but here's the general gist: I have a connection object which connects to a custom back-end server of one type or another. Clients of this connection object send requests via a method (e.g....
5
29802
by: atwomey | last post by:
When I try and place a delegate in an interface, like this : public interface ITest { double foo(); delegate void bar(); } I get an error "delegates cannot declare types". What is it about a delegate that makes it incompatible in an interface. I know that an interface cannot have any implementation - is there some implementation
5
457
by: Larry Smith | last post by:
Hi there, Given a delegate that points to a non-static member function, is there a cleaner way to change the object instance it's called on other than invoking "Delegate.CreateDelegate()" (and changing the object instance while leaving the same member function intact). Thanks in advance.
1
2410
by: somequestion | last post by:
i'd like to use delegate but it is not in same assembly. how should i do to solve this... source code is like below... using B; namespace A { class A { funcA()
7
2040
by: Dave | last post by:
I've got these declarations: public delegate void FormDisplayResultsDelegate<Type>(Type displayResultsValue); public FormDisplayResultsDelegate<stringdisplayMsgDelegate; instantiation: displayMsgDelegate = DisplayStatusMessage; implementation: public void DisplayStatusMessage(string statusMessage)
0
9688
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
9544
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
10259
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...
0
10030
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
7570
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
5467
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
5589
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3761
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2941
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.