Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic GUI Event Handling Questions C#

Good Afternoon,

I have some very basic questions on GUI Event Handling. Firstly with C# how can we link events to objects - I am guessing event handlers? If so can each handler use separate code? - How can the event handler locate the objects it must manipulate?

I have a rough idea of how it works in JAVA. Pointing me towards a reference would be fine - I have already trawled Google for answers to no avail.

Many Thanks, J

like image 482
JHarley1 Avatar asked Nov 26 '25 07:11

JHarley1


1 Answers

Firstly with C# how can we link events to objects - I am guessing event handlers? If so can each handler use separate code?

Yes, each event handler can have its own code:

class A {
    public event EventHandler SomeEvent;
}

class B {
    public B(A a) {
        a.SomeEvent += (sender, e) => { Console.WriteLine("B's handler"); };
    }
}

class C {
    public C(A a) {
        a.SomeEvent += (sender, e) => { Console.WriteLine("C's handler"); };
    }
}

How can the event handler locate the objects it must manipulate?

I'm going to oversimplify this a lot, but event handlers are essentially wrappers around the observer pattern. EventHandlers like any other Delegate type hold a list of subscribers in a method invocation list (see Delegate.GetInvocationList). You can think of it like this:

class EventHandler {
    LinkedList<Action<object, EventArgs>> subscribers =
        new LinkedList<Action<object, EventArgs>>();

    public void Add(Action<object, EventArgs> f) {
        subscribers.AddLast(f);
    }

    public void Remove(Action<object, EventArgs> f) {
        subscribers.Remove(f);
    }

    public void Invoke(object sender, EventArgs e) {
        foreach(Action<object, EventArgs> f in subscribers)
            f(sender, e);
    }
}

(The code above is pretty far removed from the actual implementation details of the real event handler class. Delegate types are immutable, so adding a handler returns a new Delegate with the handler added rather than mutating the handler in place. I believe their Add/Remove methods have a lot of threading voodoo in them as well.)

Since the delegate instance holds a reference to each of its subscribers, it has direct access to any object it manipulates.

like image 190
Juliet Avatar answered Nov 27 '25 19:11

Juliet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!