Im aware this may be a slightly odd question, but given a Page class that looks like this:
public class abc:Control
{
public abc()
{
this.Init+=new EventHandler(foo);
this.Load+=new EventHandler(foo);
}
void foo(object sender, eventargs e)
{
//determine whether or not this.Init has already fired.
}
}
I know I could do this by setting a global boolean 'hasinitfired', but I was wondering if this was not necessary or if something as part of the .net library already existed.
Why do you need to know init is fired or not. Init always gets fired during postback or callback. Go through ASP.net page lifecycle, and you will know what all events fired after init and what all before. If you intend to use same handler for different events, yes make a class variable to identify the current event. I recommend attach different handler, and call another method with different param value.
like,
public class abc:Control
{
public abc()
{
this.Init+=new EventHandler(foo1);
this.Load+=new EventHandler(foo2);
}
void foo1(object sender, eventargs e)
{
foo('init');
}
void foo2(object sender, eventargs e)
{
foo('load');
}
void foo(string from)
{
// do something
}
}
This will give cleaner solution and flexibility to add functionality.
I'm guessing you want to know if init has fired when foo runs. As #Adam said, tracing would let you do that if you wanted to see what your app was doing.
Whilst it's running, the best way as I see it would be with a flag, as you suggested.
Simon
This looks like something you'd use the .NET Trace class for. You can use trace to put text in the Visual Studio output window.
Trace.WriteLine("Method called.");
Tracing in .NET has more options than my example:
http://www.15seconds.com/issue/020910.htm
Even further to this, you could use a PostSharp aspect to decorate this method, but that is a third party library.
Related
I am learning to make a WinForm with c# and I am new to the concept of delegate. After some research on the Internet, it seems that this error arises from inconsistent between the delegate and EventHandler. but they seem fine to me, at least EventArgs definitions are the same. Please tell me what goes wrong.
I've placed this inside the Form1 constructor:
ImageRenamed += OnImageRenamed;
The following code is the custom event I would like to raise when applyBtn_Click is fired.
public delegate void ImageRenamedEventHandler(object sender, EventArgs e);
public event ImageRenamedEventHandler ImageRenamed;
protected virtual void OnImageRenamed()
{
if (ImageRenamed != null)
ImageRenamed(this, EventArgs.Empty);
}
private void applyBtn_Click(object sender, EventArgs e)
{
// do something
OnImageRenamed();
}
You don't need a custom delegate if you're seeking attachment of a method with an (object,EventArgs) signature, just use
public event EventHandler ImageRenamed;
and do away with that delegate definition
Also, you can look at changing the event invoke
protected virtual void OnImageRenamed(EventArgs e)
{
EventHandler eh = ImageRenamed;
eh?.Invoke(this, e);
}
(And call that with EventArgs.Empty)
Caching it into a local variable thus could help prevent potential issues if the handler is removed in the small window of time between using if to determine if it should be invoked and actually invoking it
If the same event will be raised for multiple different images being renamed, consider providing an EventArgs that informs the receiver which image was renamed.
I've placed this inside the Form1 constructor:
Also worth pointing out you seem to have gone wonky here. The OnImageRenamed method invokes the event and is called by the code originating the event. Classes that raise events may do so via a OnXxx method (but they don't have to)
It's not intended to be the method that handles the event. You'd do something more like:
this.ImageRenamed += <press the TAB key twice>
and VS would do something like this for you:
this.ImageRenamed = Form_ImageRenamed;
}
private void Form_ImageRenamed(object sender, EventArgs e){
throw new NotImplementedException();
}
You replace that NIE with the code you want to run when an image is renamed
Also worth noting that you don't really need the form to handle its own event, because it knows it's occurring. It's more typical to have something like an instance of a button (a self contained class) that you use on your form and attach one of your form's methods to its click event; the method that handles the event (in your form) is thus external to the class raising it (Microsoft's button). You could perhaps have another form that has the instance of the form that does the renaming and do e.g.:
renamerForm.ImageRenamed += ...
this way when renaming occurs in foreign form renamerForm a method in the local form is invoked. The sender will be renamerForm
Internally, consider an event to be little more than a list of methods (all with the same signature) that are invoked in any order when the event is raised. You append some method to the list with += and it will be accepted as long as it's signature matches. The following is also valid:
ImageRenamed += (s,e) => MessageBos.Show("The image was renamed");
You have almost done. Your OnImageRenamed needs some parameters:
protected virtual void OnImageRenamed(object sender, EventArgs e)
{
if (ImageRenamed != null)
ImageRenamed(this, EventArgs.Empty);
}
I am trying to understand events and delegates and after 2 days of studying, it looks like I am still lost in basic understanding.
I wrote following code - class UserControl contains event definition. It works well, although the program is stucked in Start() method.
How for example buttonClick event is implemented? Does button object running in some kind of different thread - on order to be able to call a method whenever the button is clicked?
Thanks
class UserControl
{
public delegate void methodsControlDelegate();
public event methodsControlDelegate methods;
public void Start()
{
while (true)
{
if (methods != null)
{
Thread.Sleep(1000);
this.methods();
}
}
}
}
class Program
{
static void Main()
{
UserControl uc = new UserControl();
uc.methods += eventMethod;
uc.Start();
}
public static void eventMethod()
{
Console.WriteLine("EVENT METHOD");
}
}
EDIT:
I have modified the code for Windows Forms.
class Writer
{
public string Text { get; set; }
public void writeMessage(object sender, EventArgs e)
{
MessageBox.Show(Text);
}
}
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
UserControl userControl = new UserControl();
Writer writer = new Writer();
userControl.WriteMessages += writer.writeMessage;
writer.Text = "HELLO, HOW ARE YOU";
}
}
class UserControl
{
public delegate void EventHandler(object sender, EventArgs e);
public event EventHandler WriteMessages;
}
I am trying to understand events and delegates and after 2 days of studying, it looks like I am still lost in basic understanding.
Take a step back.
class Customer
{
private string name;
public string Name { get { return this.name; } }
public Customer(string name)
{
this.name = name;
}
}
A property is logically a property of the class of things. Customers have a name, so Customers have a property Name.
A field is an implementation detail. It is a variable that can store a value.
A type is an implementation detail of a field or property; it gives you a restriction on what kind of data can be used as a value for this property.
The value -- say "Barbara Smith" -- is the value associated with that property for a particular customer: new Customer("Barbara Smith").
If that is not all clear then you need to take a step back and understand that. You won't get events and delegates if you haven't got properties, fields and values down.
An event is like a property. It is a logical feature of a class of things. Buttons can tell you that they are clicked, so Click is an event of Button. The button will call you when it is clicked.
A delegate type is a restriction on how the button may call you when it is clicked.
A delegate instance is a delegate to a particular function that will be called when the button is clicked.
Is that now clear?
How for example buttonClick event is implemented?
Understanding that requires you to understand how Windows works.
Every Windows program has a message queue which receives messages from the operating system. When the user clicks a button, Windows puts a message in the queue for that process that says the button was clicked. When the process handles that message, taking it out of the queue, it invokes the delegate associated with the click handler for the button.
Does button object running in some kind of different thread - on order to be able to call a method whenever the button is clicked?
Nope. If you hang the UI thread of your program so that it cannot remove the message from the queue then the button click handler is never invoked.
In fact it is illegal to call code in the button from any thread other than the UI thread.
Every time you've seen a Windows app hang, it's almost certainly because some badly-written code did not allow the message loop to take a message out of the queue in a timely manner.
You then go on to post some code with no explanation and no question. I don't know why you posted that code. Try asking a more clear question.
That said, looking at the code you seem to be trying to do event handling from a console application. Don't do that. Console applications are not event-driven. Write a WinForms or WPF application if you want to make an event-driven application.
delegate is an encapsulation on top of a method. It allows you to pass a method around, as a reference and execute it whenever you decide. The delegate defines a signature of a method and any method which is of the same signature can be used as that delegate.
events are one more level of encapsulation, this time on top of delegates. It allows adding and removing (subscribing and unsubscribing) methods to it. And when the event fires, it will invoke each one of the added to it methods (delegates). This encapsulation is necessary, so that one 'client' of the event cannot override another client to the same event.
i got code inglobal.asax page:
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
System.Timers.Timer timScheduledTask = new System.Timers.Timer();
// Timer interval is set in miliseconds,
// In this case, we'll run a task every minute
timScheduledTask.Interval = 60 * 1000;
timScheduledTask.Enabled = true;
// Add handler for Elapsed event
timScheduledTask.Elapsed += new System.Timers.ElapsedEventHandler(timScheduledTask_Elapsed);
}
void timScheduledTask_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
// Over here i want to call function that i have in asp.net page
}
my problem here that in timScheduledTask_Elapsed function, i want to call to function that i have in asp.net page (Contacts.aspx.cs).
Any idea how to call this function??
It would need to be a static method of the page as the application class has no way of knowing the current page instance.
A rough example can be seen below.
somepage.aspx:
public class SomePage : Page
{
public static void DoSomething()
{
...
}
}
global.asax:
void Application_Start(object sender, EventArgs e)
{
...
// Add handler for Elapsed event
timScheduledTask.Elapsed += new System.Timers.ElapsedEventHandler(timScheduledTask_Elapsed);
}
void timScheduledTask_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
SomePage.DoSomething();
}
However, this does mean that anything in DoSomething() must not rely on anything instance specific in the page.
I would rethink your approach.
Also note that timers are a bad idea here IMHO, if the application process unloads your timers will never get called so you cannot really rely on them.
If you need to call a PAGE method from outside, you have a very bad design. Before doing anything else I'd advise you to do some research on separating your code into multiple layers, so such situation can never happen.
If you however still insist you want to do it your way (you'll understand sooner or later anyway), simplest solution is to make the requested page method static. That way you can call it anytime without a reference to an actual instance.
I'd make the code into a non-visual class and call it.
If you need it to be visual, make it a visual user control and include it on a master page that you use.
I agree that trying to call something on a different page when that's not the page running is just asking for problems.
I have one main windows form and within that form I have custom controls that represents different screens in application. I want to access this control's child controls. There's something I'm not getting here...sometimes I get this error:
Cross-thread operation not valid:
Control 'lblText' accessed from a thread
other than the thread it was created on.
but sometimes everything works OK. I don't completelly understand why the error...probably something with external device (MEI BillAcceptor) which has an event (inside Form1 class) that does the changes to the control... so let me write a simple code...
//user control
public partial class Screen2 : UserControl
{
public void changeValue(string txt)
{
lblText.Text = txt;
}
}
and the method changeValue is called from a form1 when particular event is rised...
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
BillAcceptor.SomeBillAcceptorEvent +=
new SomeBillAcceptorEventHandler(changeText);
}
private void changeText(object sender, EventArgs args)
{
_screen2.changeValue("some text");
}
}
So the most annoying thing is that sometimes everything actually works... So my question is "do I have to use Invoke here?" or how do I solve this with less changes to the application...
In your handler. do something like this.
if (this.InvokeRequired)
{
Invoke(new MethodInvoker(() =>
{
_screen2.changeValue("some text");
}));
}
else
{
_screen2.changeValue("some text");
}
I would guess that the event is being raised on a seperate thread other that the main UI thread.
Yes you need to use Invoke if there is a possibility of that method being called from a different thread.
You can check this.InvokeRequired(), if true, then use invoke, if false do a normal call.
This occurs due to thread unsafe call
You should make only thread safe calls in program
Check this link.
The short answer is yes, you must use Invoke. See this question and its accepted answer if you need details.
The reason the exception is only thrown some of the time, by the way, comes down to timing. You currently have a race condition in which sometimes you get lucky and sometimes you don't.
By the way, here is pretty handy pattern for this sort of thing.
Refactor any code that sets form values into its own private void method(s).
In this new method, call InvokeRequired. If it returns true, call Invoke, passing the current method so as to recurse back into it. If it returns false, go ahead and make the change.
Call this new method from the event handler.
For example:
private void ChangeScreen2() {
if (this.InvokeRequired) {
this.Invoke(new MethodInvoker(ChangeScreen2));
}
else {
_screen2.changeValue("some text");
}
}
private void changeText(object sender, EventArgs args)
{
ChangeScreen2();
}
The idea being that you sequester all code that modifies the form into these methods that always begin with a check of InvokeRequired and always Invoke themselves if so required. This pattern works with .NET 1.0 onward. For even neater approach, see the accepted answer to this question, which works with .NET 3.0 and later.
I am studying events in C# but there are not much articles or information that show me where or what kinda position I'd need to use events in.
Could some one give me real world example that makes them more understandable.
Thanks in advance.
As Chris Gray said, one use is to signal when something has happened that your code didn't directly call. The most common cause here is probably user actions on the GUI. Another example might be an asynchronous operation completing on another thread.
The other reason to use events is when you don't know who might be interested in what has just happened. The class raising the event doesn't need to know (at design time) anything about how many instances of what other classes might be interested.
class Raiser {
public DoSomething() {
//Do something long winded.
OnDidSomething(new DidSomethingEventArgs());
}
public EventHandler<DidSomethingEventArgs> DidSomething;
private OnDidSomething(DidSomethingEventArgs e) {
if (DidSomething != null)
DidSomething(this, e);
}
}
Obviously, you also need to define the DidSomethingEventArgs class which passes on the relevant data about the event. This also illustrates a common naming convention for events. If the event is called X, then the event is only ever raised in a method called OnX and any data it passes on is an instance of class XEventArgs. Note that an event can be null if no listeners are subscribed to it, hence the check just before we raise the event.
Note that this class knows nothing about what other classes might be interested in the fact that it did something. It simply announces the fact that it has done it.
Multiple classes can then listen out for the event:
class ListenerA {
private Raiser r;
ListenerA(Raiser r) {
this.r = r;
r.DidSomething += R_DidSomething;
}
R_DidSomething(object sender, DidSomethingEventArgs e) {
//Do something with the result.
}
}
And:
class ListenerB {
private Raiser r;
ListenerB(Raiser r) {
this.r = r;
r.DidSomething += R_DidSomething;
}
R_DidSomething(object sender, DidSomethingEventArgs e) {
//Do something with the result.
}
}
Now, when the DoSomething method is called on the Raiser instance, all instances of ListenerA and ListenerB will be informed via the DidSomething event. Note that the listener classes could easily be in different assemblies to the raiser. They need a reference back to the raiser's assembly but it doesn't need a reference to its listeners' assemblies.
Note that the above simple Raiser example may cause you some problems in a multi-threaded program. A more robust example would use something like:
class Raiser {
public DoSomething() {
//Do something long winded.
OnDidSomething(new DidSomethingEventArgs());
}
#region DidSomething Event
private object _DidSomethingLock = new object();
private EventHandler<DidSomethingEventArgs> _DidSomething;
public EventHandler<DidSomethingEventArgs> DidSomething {
add { lock(_DidSomethinglock) _DidSomething += value; }
remove { lock(_DidSomethinglock) _DidSomething -= value; }
}
OnDidSomething(DidSomethingEventArgs e) {
EventHandler<DidSomethingEventArgs> handler;
lock (_DidSomethingLock)
handler = _DidSomething;
if (handler == null)
return;
try {
DidSomething(this, e);
} catch (Exception ex) {
//Do something with the exception
}
}
#endregion
}
This ensures that another thread adding or removing a listener while you are in the middle of raising the event doesn't cause problems.
The simple listeners used here will also cause memory leaks if instances of the listener classes are being created and destroyed. This is because the Raiser instance gets passed (and stores) a reference to each listener as they subscribe to the event. This is enough to prevent the garbage collector from properly tidying up the listeners when all explicit references to them are removed. The best way round this is probably to make the listeners implement the IDisposable interface and to unsubscribe from the events in the Dispose method. Then you just need to remember to call the Dispose method.
The most practical example I generally see is User Interactivity. Let's use a Button as a specific example. When the button is clicked, you obviously want something to happen. Let's say we call "SaveSettings()". However, we don't want to hard-code "SaveSettings()" into the button. The buttom would be commanding SaveSettings() to occur. Obviously, this prevents the button from being reusable - we can't use a button which calls SaveSettings() anywhere but the settings dialog. To avoid writing the same button code for every button, each one calling a different function, we use an event.
Instead of the button calling a function directly, the button announces that it has been clicked. From there, the button's responsibility is over. Other code can listen for that announcement, or event, and do something specific.
So in our SaveSettings example, the settings dialog code finds the "OK" button and listens for its "I got clicked" announcement, and when it is fired, calls SaveSettings().
Events can become very powerful because any number of different listeners can wait for the same event. Many things can be invoked by the event.
Sure thing. think of an event as the notification that occurs when something completes in the system that your code didn’t directly call. In C# it's really easy to get code to run when an event "fires"
For example when a user presses a button an event will be raised or when a background network operation completes. In C# you use the += semantics to attach to the event that will be “signaled” when the event fires.
I made you a simple C# winforms program – in it I added a button using the Visual Studio “Designer” (I just dragged a button from the Toolbox to the Window).
You’ll see the line “button1.Click” – in this case I want to do something when the “Click” event is raised.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace events
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
button1.Click += new EventHandler(button1_Click);
}
void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("Hi!");
}
}
}
You’ll also see other kinds of events in practice for example:
Network operation has completed (WebClient.DownloadFileCompleted)
User Interfaces (resizing windows for example)
Timers (set off the timer in 10 minutes)
Let's say you are developing a UI. You create a widget and you add it to the main form. When something happens in your widget, you can use events to trigger some action on the form - disabling other buttons, etc.
Just like how a button's click event works.