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
27 2323
Have a look at properties, you can build the event raiser from the set block. eg: - private static int _ANumber = 5;
-
-
public static int ANumber
-
{
-
get { return _ANumber; }
-
set
-
{
-
_ANumber = value;
-
//Event would be fired here.
-
}
-
}
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
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?
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.
yes AmzBee, u r spot on on this.
Let me clear the scenario once again. -
namespace asd
-
{
-
class abc //my main class running the form is running
-
{
-
// the variable for which i want to create a listener.
-
public static int i;
-
-
// function that i want to call once the change in value is notified by event listener
-
public void fn()
-
{
-
}
-
-
}
-
}
-
-
// this is a library which is called by some other class
-
using asd;
-
namespace dsa
-
{
-
Class lib
-
{
-
public static setvalue()
-
{
-
// will be able to change the value of abc class variable i as it is static.
-
abc.i =10;
-
/// once this value is set i want to notify abc class about the change. Which inturn will call the function fn().
-
}
-
}
-
-
}
-
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
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: -
public static class clsTest
-
{
-
public delegate void MyEventHandler(string message, DateTime when);
-
public static event MyEventHandler MyEvent;
-
-
static clsTest()
-
{
-
// Adds our internal subscriber.
-
MyEvent += new MyEventHandler(clsTest_MyEvent);
-
}
-
-
static void clsTest_MyEvent(string message, DateTime when)
-
{
-
// Events require atleast 1 subscriber.
-
}
-
-
public static void FireEvent(string message)
-
{
-
MyEvent(message, DateTime.Now);
-
}
-
}
-
And here is a form i created: -
public partial class Form1 : Form
-
{
-
public Form1()
-
{
-
InitializeComponent();
-
clsTest.MyEvent += new clsTest.MyEventHandler(clsTest_MyEvent);
-
}
-
-
void clsTest_MyEvent(string message, DateTime when)
-
{
-
this.BeginInvoke( new clsTest.MyEventHandler(HandleEvent), message, when );
-
}
-
-
void HandleEvent(string message, DateTime when)
-
{
-
string msg = string.Format("Message: {0} \r\n At: {1}", message, when);
-
MessageBox.Show(msg);
-
}
-
-
private void button1_Click(object sender, EventArgs e)
-
{
-
clsTest.FireEvent("hello");
-
}
-
-
}
-
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!
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. -
namespace abc
-
{
-
class asd
-
{
-
public static int x;
-
// want an eventlistener or a way to call a function asd
-
public asd()
-
{
-
//having code to access non static variable so can not be static.
-
}
-
public static void Main()
-
{
-
xyz.setValue();
-
}
-
}
-
-
class xyz
-
{
-
public statis void setValue()
-
{
-
asd.x = 10; // At this instant of time the event should notify
-
// class asd about the change in value.
-
}
-
}
-
}
-
Please let me know if i am able to convey u my requirement this time :)
- class asd {
-
public static event Action<int> XChanged;
-
-
private static int _x;
-
-
public static int x {
-
get { return _x; }
-
set {
-
if (value != x) {
-
_x = value;
-
if (XChanged != null)
-
XChanged(x);
-
}
-
}
-
}
-
-
// Constructor
-
public asd() {
-
XChanged += EventHandlingMethod;
-
}
-
-
void EventHandlingMethod(int newValue) {
-
// Do something
-
}
-
}
-
-
class xyz {
-
public void setValue() {
-
asd.x = 1; // the event should be fired after setting x to 1
-
}
-
}
@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.
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. -
-
namespace StaticEvent
-
{
-
public class VuserData
-
{
-
public static event Action<int> Xchanged;
-
-
private static int _x;
-
-
public static int x
-
{
-
get
-
{
-
return _x;
-
}
-
set
-
{
-
if (value != x)
-
_x = value;
-
Xchanged(x);
-
}
-
}
-
-
public VuserData()
-
{
-
Xchanged += new Action<int>(VuserData_Xchanged);
-
}
-
-
void VuserData_Xchanged(int obj)
-
{
-
Console.WriteLine("{0}", obj);
-
}
-
public static void Main()
-
{
-
Test.sMain();
-
}
-
}
-
-
class Test
-
{
-
public static void sMain()
-
{
-
VuserData.x = 1;
-
}
-
}
-
}
-
-
On line 20:
Xchanged(x);
You've to check first, if Xchanged isn't null! -
if(Xchanged != null)
-
Xchanged(x);
-
@ChBinder
In that case the Xchanged(x) is never called.
What am i missing over here.
You never create an object of type VuserData like -
VuserData obj1 = new VuserData();
-
At least when you create an object of type VuserData it will be attached to the Changed-Event
Read my last reply, give's the valid way of firing events inside of a class.
@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. :)
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.
@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.
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.
@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.
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?
@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.
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?
@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.
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.
@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.
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.
@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 :)
Sign in to post your reply or Sign up for a free account.
Similar topics
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...
|
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...
|
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...
|
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...
|
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) &...
|
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'...
|
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...
|
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...
|
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...
|
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...
|
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...
|
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...
|
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...
|
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...
|
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$) {
}
...
|
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...
|
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
|
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...
|
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...
| |