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.
Related
So I'm working with SdlDotNet - which basically converts SDL calls into what C# should look like and I ran into an issue.
That issue being that because the SdlDotNet is running in a different class to the main part of my application - I can't detect when it's closing.
The SdlDotNet library has an event that fires when it is told to close, and that event is:
SdlDotNet.Core.Events.Quit
In the object viewer - the event is shown as such:
public static event System.EventHandler<QuitEventArgs> Quit
Member of SdlDotNet.Core.Events
What I've done, is there is a main Windows form application that calls upon the SDL class like so:
private void drawToScreen()
{
//Starts the SDL off drawing to the screen
SDLDraw sdl = new SDLDraw();
sdl.startDrawing();
//How would I go about detecting SdlDotNet.Events.Quit
//From the class I've instanced
//When I was on my original Windows Forms implementation
//It worked like this:
////sdl.FormClosed += new FormClosedEventHandler(detectClose);
//But just copying that structure and trying
////sdl.Events.Quit += new QuitArgs(detectClose);
//Doesn't have the same effect, because sdl does not contain a definition for 'Events'
}
private void detectClose(object sender, QuitArgs e)
{
MessageBox.Show("SDL closed!")
}
So, I guess the question is how do I listen for Events.Quit firing in the class I called from the class I called it from?
Thanks in advance!
The declaration reveals that this is a static event, therefore it is associated with the class, not an instance. Use
SdlDotNet.Core.Events.Quit += new QuitArgs(detectClose);
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.
Forgive me if this is a bit garbled, I'm a bit new on Windows Forms, having spent months in ASP.NET
Basically, I am using Quartz.NET in my Windows Form application - when a job is executed, it fires another class file - the parameters it passes in do not contain a reference to the form, and I don't think I can change this.
What I want to do is refresh a grid on the page after the job executes - and the only place that 'tells' me a job has been executed are in other files, rather than the forms code. I can't figure out a way of accessing methods/objects on the form without starting a new instance of it, which I don't want to do.
EDIT: To sum up, I just want a way to sent a message or something to the already open Main form from another class
Why not raise event from your class to winform. Thats the elegant way to do this. To do send message, you can use interop to call sendMessage which requires handle of the window
Actualy, if members of a class were not static, you wont be able to access them without an instance of that class. Try to accuire the same instance of the class that your actions are applied on it.
The easiest way is to pass the instance of the main form to the class consuming the Quartz.NET event, so that the consuming class can then call methods on the main form. I'm guessing that class would be created in the main form somewhere anyway, so it would be something like:
var quartzConsumer = new QuartzConsumer(this);
...
class QuartzConsumer {
MainForm _form;
public QuartzConsumer(MainForm form) {
_form = form;
...
}
void OnTimer(..) {
_form.UpdateGrid();
}
}
EDIT as #hundryMind says, another solution is for the main form to subscribe to an event on the consuming class:
class QuartzConsumer {
public delegate void DataChangedEventHandler();
public event DataChangedEventHandler DataChanged;
void OnTimer(..) {
if (this.DataChanged != null) this.DataChanged();
}
}
// in MainForm:
var quartzConsumer = new QuartzConsumer(..);
quartzConsumer.DataChanged += this.OnDataChanged;
...
void OnDataChanged() {
// update the grid
}
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.
What is the best design decision for a 'top-level' class to attach to an event to a class that may be '5+ layers down in the callstack?
For example, perhaps the MainForm has spawned an object, and that object has spawned a callstack of several other object calls. The most obvious way would be to chain the event up the object hierarchy, but this seems messy and requires a lot of work.
One other solution ive seen is to use the observer pattern by creating a publically accessible static object which exposes the event, and acts as a proxy between the bottom-level object, and the top-level 'form'.
Any recommendations?
Here's a pseudo-code example. In this example, the MainForm instantiates 'SomeObject', and attaches to an event. 'SomeObject' attaches to an object it instantiates, in an effort to carry the event up to the MainForm listener.
class Mainform
{
public void OnLoad()
{
SomeObject someObject = new SomeObject();
someObject.OnSomeEvent += MyHandler;
someObject.DoStuff();
}
public void MyHandler()
{
}
}
class SomeObject
{
public void DoStuff()
{
SomeOtherObject otherObject = new SomeOtherObject();
otherObject.OnSomeEvent += MyHandler;
otherObject.DoStuff();
}
public void MyHandler()
{
if( OnSomeEvent != null )
OnSomeEvent();
}
public event Action OnSomeEvent;
}
If your application isn't based on Composite UI Application Blocks, the easiest solution is to put a "listener" class between Main form and your other components which both classes can easily access. Conceptually, the classes are laid out as follows:
---------- ----------------
| MainForm | | Some Component |
--------- ----------------
| |
Hooks onto Notifies
| |
\ /
-----------------
| Proxy Notifier |
-----------------
Here's some example code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
FakeMainForm form = new FakeMainForm();
form.CreateComponentAndListenForMessage();
Console.ReadKey(true);
}
}
class FakeMainForm
{
public FakeMainForm()
{
Listener.AddListener(MessageRecieved);
}
void MessageRecieved(string msg)
{
Console.WriteLine("FakeMainForm.MessageRecieved: {0}", msg);
}
public void CreateComponentAndListenForMessage()
{
ComponentClass component = new ComponentClass();
component.PretendToProcessData();
}
}
class Listener
{
private static event Action<string> Notify;
public static void AddListener(Action<string> handler)
{
Notify += handler;
}
public static void InvokeListener(string msg)
{
if (Notify != null) { Notify(msg); }
}
}
class ComponentClass
{
public void PretendToProcessData()
{
Listener.InvokeListener("ComponentClass.PretendToProcessData() was called");
}
}
}
This program outputs the following:
FakeMainForm.MessageRecieved: ComponentClass.PretendToProcessData() was called
This code allows you to invoke methods directly on any listener, no matter how far apart they are in the call stack.
Its easy to rewrite your Listener class so that its a little more generic and works on different types, but you should get the idea.
My initial intention would be to try and avoid that, so that an object's scope has obvious boundaries. In the particular case of Forms, I would attempt to have the child's parent form manage all required communications withs its ancestors. Can you be more specific about your case?
My first thought is that from your MainForm's perspective, it should have no idea what is going on 5 levels down. It should only know about its interactions with the object that it spawned.
With that, if you main form wants to perform some action asynchronously, it should be able to do that by calling a method on the spawned object asynchronously.
Now from your spawned object's point of view, if you allowed your caller to perform some method asynchronously, there's no need to push the event model further down... just call the methods directly down the stack. You're already on another thread.
Hopefully that helps a little. Just remember the levels of your app should only be aware of what goes on in the level immediately below them.
WPF uses routed events. These are static and can bubble up or tunnel down the element tree. I don't know if you are using WPF, but the idea of static events might help you out.
I wouldn't say this is a design fault, there are valid reasons for the main form to want to listen to what an object is doing. One scenario I've encountered is displaying status messages to the user to indicate what background processes are doing, or what multiple controls are doing in a multi-threaded app that lets you have multiple screens/"pages" open at once.
In the Composite UI Application Block, the basic equivalent of a dependency injection container wires up events when its instantiating objects in the same work item (a work item is just an object container for a group of related user controls). It does this by scanning for special attributes such as [EventPublication("StatusChanged")] on events and [EventSubscription("StatusChanged")] on public methods. One of my applications uses this functionality so that a user control instantiated way down in the innards of the application can broadcast status information (such as "Loading customer data...45%") without knowing that that data is going to end up in the main form's status bar.
So a UserControl can do something like this:
public void DoSomethingInTheBackground()
{
using (StatusNotification sn = new StatusNotification(this.WorkItem))
{
sn.Message("Loading customer data...", 33);
// Block while loading the customer data....
sn.Message("Loading order history...", 66);
// Block while loading the order history...
sn.Message("Done!", 100);
}
}
...where the StatusNotification class has an event with the a signature like
[EventPublication("StatusChanged")]
public event EventHandler<StatusEventArgs> StatusChanged;
... and the above Message() and Dispose() methods on that class invoke that event appropriately. But that class didn't explicitly have that event hooked up to anything. The object instantiator will have automatically hooked up the events to anybody with a subscription attribute of the same name.
So the MainForm has an event handler that looks something like this:
[EventSubscription("StatusChanged", ThreadOption=ThreadOption.UserInterface)]
public void OnStatusChanged(object sender, StatusEventArgs e)
{
this.statusLabel.Text = e.Text;
if (e.ProgressPercentage != -1)
{
this.progressBar.Visible = true;
this.progressBar.Value = e.ProgressPercentage;
}
}
... or some such. It's more complicated than that since it will rotate through multiple status notifications for a given number of seconds since multiple user controls can be broadcasting status messages around the same time.
So to recreate this behavior without actually switching over to CAB (which, to be honest, is much more complicated than I think it really needs to be), you could either have a MessageNotificationService object that you pass around your application or that you turn into a static/singleton object (I usually avoid this approach since it's harder to test), OR you could have you sub usercontrols be instantiated by a factory class that does the event wiring up for you. Objects could register with the factory by attributes of your own creation or by explicitly calling methods that say "hey, anytime you create an object with an event of this signature, I want to know about it."
Just be careful to have whatever class you implement unhook the events when an object gets disposed because it's stupid easy in this scenario to end up with something that won't get garbage collected.
Hope this helps!