473,382 Members | 1,424 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,382 software developers and data experts.

Event Handling in C#

Hi All,

I want to create a event on a static variable of the class.
The intention is to notify the class whenever the static variable value is changed, so that it can do some processings.

Please help me do this.
Thanks & Regards
Nishant Guarav
Jul 26 '10 #1
27 2323
Aimee Bailey
197 Expert 100+
Have a look at properties, you can build the event raiser from the set block. eg:

Expand|Select|Wrap|Line Numbers
  1. private static int _ANumber = 5;
  2.  
  3. public static int ANumber
  4. {
  5.   get { return _ANumber; }
  6.   set 
  7.   {
  8.     _ANumber = value;
  9.     //Event would be fired here.
  10.   }
  11. }
Jul 26 '10 #2
thanks AmzBee for the response, i did the same thing but was not able to get the event handler respond to that, when the static value was changed in some other class.
It will be of great help if u can show it with a example how this can be done.

Thanks & Regards
Nishant Gaurav
Jul 26 '10 #3
Christian Binder
218 Expert 100+
Hi!

Please provide the code you've actually written, so I'd be able to find out what you've done wrong.

Who do you want to notify when the property's value is changed? The static class or any instance of this class?
Jul 26 '10 #4
Aimee Bailey
197 Expert 100+
Be aware that firing events outside of a form will most likely cause a cross-thread exception, im taking a stab in the dark that your trying to update a form?

Aimee.
Jul 26 '10 #5
yes AmzBee, u r spot on on this.
Let me clear the scenario once again.

Expand|Select|Wrap|Line Numbers
  1. namespace asd
  2. {
  3. class abc //my main class running the form is running
  4. {
  5.   // the variable for which i want to create a listener.
  6.   public static int i;
  7.  
  8.   // function that i want to call once the change in value is notified by event listener
  9.   public void fn()
  10.   {
  11.   }
  12.  
  13. }
  14. }
  15.  
  16. // this is a library which is called by some other class
  17. using asd;
  18. namespace dsa
  19. {
  20. Class lib
  21. {
  22.   public static setvalue()
  23.   {
  24.     // will be able to change the value of abc class variable i as it is static.
  25.     abc.i =10;
  26.     /// once this value is set i want to notify abc class about the change. Which inturn will call the function fn().
  27.   }
  28. }
  29.  
  30. }
  31.  
any Help on this thing will be of great help.
If there is some another way of doing this, i want to know that too..

i want the most efficient way of doing this thing.

Thanks & Regards
Nishant Gaurav
Jul 26 '10 #6
Aimee Bailey
197 Expert 100+
To be honest this area is a quite clouded one, and ive found many people find it hard to deal with events in c#, id reccomend checking out MDSN on the topic of events and delegates, however as im in the giving mood hehe, here is the most elegant way to handle events within static classes:

This is the external static class:
Expand|Select|Wrap|Line Numbers
  1. public static class clsTest
  2.     {
  3.         public delegate void MyEventHandler(string message, DateTime when);
  4.         public static event MyEventHandler MyEvent;
  5.  
  6.         static clsTest()
  7.         {
  8.             // Adds our internal subscriber.
  9.             MyEvent += new MyEventHandler(clsTest_MyEvent);
  10.         }
  11.  
  12.         static void clsTest_MyEvent(string message, DateTime when)
  13.         {
  14.             // Events require atleast 1 subscriber.
  15.         }
  16.  
  17.         public static void FireEvent(string message)
  18.         {
  19.             MyEvent(message, DateTime.Now);
  20.         }
  21.     }
  22.  
And here is a form i created:
Expand|Select|Wrap|Line Numbers
  1. public partial class Form1 : Form
  2.     {
  3.         public Form1()
  4.         {
  5.             InitializeComponent();
  6.             clsTest.MyEvent += new clsTest.MyEventHandler(clsTest_MyEvent);
  7.         }
  8.  
  9.         void clsTest_MyEvent(string message, DateTime when)
  10.         {
  11.             this.BeginInvoke(  new clsTest.MyEventHandler(HandleEvent), message, when );
  12.         }
  13.  
  14.         void HandleEvent(string message, DateTime when)
  15.         {
  16.             string msg = string.Format("Message: {0} \r\n At: {1}", message, when);
  17.             MessageBox.Show(msg);
  18.         }
  19.  
  20.         private void button1_Click(object sender, EventArgs e)
  21.         {
  22.             clsTest.FireEvent("hello");
  23.         }
  24.  
  25.     }
  26.  
Make note that i actually subscribe to the event twice, this is because an event is required to have atleast one subscriber on initialization.

Also, to raise the event like in visual basic, all you need do is call the event and pass it the arguments specified in the delegate.

I know this is a bit of a verbose answer, and il probably be told off for it, but hey if it helps!
Jul 26 '10 #7
Hi AmzBee/ChBinder,
Sorry but i didn't get the info that i intended for.
Or may be i am not able to understand in what way it is potraying the scenario i informed about.

For that case let me again specify the need.

Expand|Select|Wrap|Line Numbers
  1. namespace abc
  2. {
  3.     class asd
  4.     {
  5.         public static int x;
  6.         // want an eventlistener or a way to call a function asd
  7.         public asd()
  8.         {
  9.             //having code to access non static variable so can not be static.
  10.         }
  11.         public static void Main()
  12.         {
  13.             xyz.setValue();
  14.         }
  15.     }
  16.  
  17.     class xyz
  18.     {
  19.         public statis void setValue()
  20.         {
  21.             asd.x = 10; // At this instant of time the event should notify 
  22.             // class asd about the change in value.
  23.         }
  24.     }
  25. }
  26.  
Please let me know if i am able to convey u my requirement this time :)
Jul 26 '10 #8
Christian Binder
218 Expert 100+
Expand|Select|Wrap|Line Numbers
  1. class asd {
  2.     public static event Action<int> XChanged;
  3.  
  4.     private static int _x;
  5.  
  6.     public static int x {
  7.       get { return _x; }
  8.       set {
  9.         if (value != x) {
  10.           _x = value;
  11.           if (XChanged != null)
  12.             XChanged(x);
  13.         }
  14.       }
  15.     }
  16.  
  17.     // Constructor
  18.     public asd() {
  19.       XChanged += EventHandlingMethod;
  20.     }
  21.  
  22.     void EventHandlingMethod(int newValue) {
  23.       // Do something
  24.     }
  25.   }
  26.  
  27.   class xyz {
  28.     public void setValue() {
  29.       asd.x = 1; // the event should be fired after setting x to 1
  30.     }
  31.   }
Jul 26 '10 #9
@ChBinder
Hi chBinder,
Thanks for the above code, but
the above code gives error at XChanged(x);
The error is:
System.NullReferenceException: Object reference not set to an instance of an object.

It will be really helpful if u tell me what has gone wrong in this case.
Jul 26 '10 #10
Hi chBinder,
Thanks for the above code, but
the above code gives error at XChanged(x);
The error is:
System.NullReferenceException: Object reference not set to an instance of an object.

It will be really helpful if u tell me what has gone wrong in this case.
As per the code Xchanged is a public static variab;e so there is no need to create the instance.

i am putting here the code that i tested with ur code.
Expand|Select|Wrap|Line Numbers
  1.  
  2. namespace StaticEvent
  3. {
  4.     public class VuserData
  5.     {
  6.         public static event Action<int> Xchanged;
  7.  
  8.         private static int _x;
  9.  
  10.         public static int x
  11.         {
  12.             get
  13.             {
  14.                 return _x;
  15.             }
  16.             set
  17.             {
  18.                 if (value != x)
  19.                     _x = value;
  20.                 Xchanged(x);
  21.             }
  22.         }
  23.  
  24.         public VuserData()
  25.         {
  26.             Xchanged += new Action<int>(VuserData_Xchanged);
  27.         }
  28.  
  29.         void VuserData_Xchanged(int obj)
  30.         {
  31.             Console.WriteLine("{0}", obj);
  32.         }
  33.         public static void Main()
  34.         {
  35.             Test.sMain();
  36.         }
  37.     }
  38.  
  39.     class Test
  40.     {
  41.         public static void sMain()
  42.         {
  43.             VuserData.x = 1;
  44.         }
  45.     }
  46. }
  47.  
  48.  
Jul 26 '10 #11
Christian Binder
218 Expert 100+
On line 20:
Xchanged(x);
You've to check first, if Xchanged isn't null!

Expand|Select|Wrap|Line Numbers
  1. if(Xchanged != null)
  2.   Xchanged(x);
  3.  
Jul 26 '10 #12
@ChBinder
In that case the Xchanged(x) is never called.
What am i missing over here.
Jul 26 '10 #13
Christian Binder
218 Expert 100+
You never create an object of type VuserData like
Expand|Select|Wrap|Line Numbers
  1. VuserData obj1 = new VuserData();
  2.  
At least when you create an object of type VuserData it will be attached to the Changed-Event
Jul 26 '10 #14
Aimee Bailey
197 Expert 100+
Read my last reply, give's the valid way of firing events inside of a class.
Jul 26 '10 #15
@AmzBee
Hi AmzBee,

It will be great if u can help me understand how the method u told is more valid and accurate.

p.s i am a beginner and really appreicaite if u can help me out. :)
Jul 27 '10 #16
Christian Binder
218 Expert 100+
I think the main difference to AmzBee's code is, that I'm not using a static constructor.
You could also use a static constructor and attach to the event. So it will be handled although there isn't an instance of the object.
You can also use a static constructor and a non-static constructor.

It's depending on what you want to achieve at last.
Jul 27 '10 #17
@ChBinder
Thanks ChBinder,
The thing is with a static constructor, it will require a static method to be invoked which means that the method VuserData_Xchanged at Line No 29 in the above example should be static. which i dont want to be.

what i want to know is if there is any difference in terms of performance with the above to sited examples.
And if it is there then which is the best approach.
Jul 27 '10 #18
Christian Binder
218 Expert 100+
It is difficult to tell you the best approach without knowing the overall picture.

What do you want to do when the event comes?
How many instances of VuserData you'll create?
What is the whole thing intended to do?

There are many "best approaches", they all depend on what your program is going to do.
Jul 27 '10 #19
@ChBinder
The thing is there will be only one instance of vuser.
the other class is actually a library referencing this vuser class.
And as the variable is static i will not be required to create any other instance for that.
this library is inturn being referenced by the vuser class in other way.

please let me know if u want any other information.
Jul 27 '10 #20
Christian Binder
218 Expert 100+
Okay, so you've got only one instance of VuserData, why do you need a static variable, you could also use a non-static for it as long as there's only 1 instance.

Which (event-handler-)method do you want to call? My first code-suggestion shows how to do it with a non-static method of VuserData-class. Is this what you've wanted?
Jul 27 '10 #21
@ChBinder
The static variable is required because that is being modified by the 2nd class which a library and not the same class.
If i would have to use the non static variable that will mean that i have to create an instance of the class first and then update the value.
Jul 27 '10 #22
Christian Binder
218 Expert 100+
Ok, I understand. But what will you do, when the event is fired?
You've got one instance of VuserData-class, do you want to execute code of a method of this instance?
Jul 27 '10 #23
@ChBinder
yes thats the whole idea...
the only instance created for vuser has some private non static members too, which i will be using in the member of that class.

Basically,
u can see the approach as a client server one.
In which vuser instance is the server running.
and the other class which is modifying the static variable of the vuser class is a client.
and for that reason i dont want the client to create a instance of the server class in this case the vuser.
Jul 27 '10 #24
Christian Binder
218 Expert 100+
How do you separate server and client?
If you've got two different processes (starting the program (exe) twice or starting different programs), your approach won't work because the static variable is per process.
Jul 27 '10 #25
@ChBinder
there are 2 application exe's. 1 server and 1 client.
there is a dll which is common to both server and clients.

Basically I want to bridge the 2 exe's and i am not getting a workaround.

i want to send some information from client to server.
i was working in that direction itself in order to achieve the client server communication.
but now i dont know what to do.
It will be great if u can help me in this.
Jul 27 '10 #26
Christian Binder
218 Expert 100+
Good, so the static variable will be unuseable when there are two instances running.
The most simple way (for me) to let two programs talk to each other ist unsing files or databases which you've to poll and check for changes - it's also the most dirty way I think.

Better ways are using Named Pipes or WCF-technology. But these are greater constructs, so you've to dig into these concepts to be able to use them.
Jul 27 '10 #27
@ChBinder
Thanks both of u for ur help on event handling.
i really appreciate ur help.
I will mark this thread as completed. As now what i need is completely different from the context set for this discussion.
Thanks once again :)
Jul 27 '10 #28

Sign in to post your reply or Sign up for a free account.

Similar topics

4
by: hillcountry74 | last post by:
Hi, I'm a newbie and trying to understand event handling in c#. I have understood handling events using delelgate objects. But not this method- "Event handling by overriding the virtual...
3
by: Ashok Kumar K | last post by:
Hi all, Where can I get some insight on using the __hook, __unhook, event_source and event_receiver for specifically COM events. The documentation given in MSDN is very minimal. I have the...
9
by: Sridhar | last post by:
Hi, I have created a web page which includes a place holder. I also have a dropdown list in that webpage. when I select one of the choices in that dropdown list, It will load a user control...
2
by: Paul E. Orman | last post by:
I have a piece of VB code (.NET 1.1 - VB 2003) that loads data from a database through a timer. So the timer is setup and from it I call the procedure that loads the latest records from the...
3
by: johncee | last post by:
Greetings, I created a base class that has a datagrid. I've made it generic as possible so that any derived classes pass some info to the base constructor (including a SQL select stmt) &...
4
by: reggiestyles | last post by:
Hi, I've got a question about prototype and event handling. I've got several div's (dynamic number) on a page that I want to set as active or inactive (basically, I'm using scriptaculous'...
2
by: a | last post by:
Hi I have a 3-column listview. It has to return the value of the cell when the user click the listview. The SelectedIndexChanged event and ItemSelectionChanged Event only return the row...
3
by: a | last post by:
Hi, I have a 3-column listview. It has to return the value of the cell when the user click the listview. The SelectedIndexChanged event and ItemSelectionChanged Event only return the row...
1
by: stmfc | last post by:
hi, for an event handling mechanism, we need an event object. (the object where the event actually occur) and we need an event handler, and we need a registration of the event handler to the...
5
by: Klaudiusz Bryja | last post by:
Hi, This is for NetCF 2.0. I need to create event handling code which using reflection. I have some parameters in XML which describe how event should be handled. I have code to create...
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: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
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.