I'm trying to use a class to simplify dynamically binding and unbinding a method callback to a delegate. When the Bound property is changed to a different value, the callback is added or removed from the actionEvent delegate depending on whether bound is true or false.
public class Binding
{
private bool bound;
private Action actionEvent;
private Action callback;
//Constructor
public Binding(ref Action actionEvent, Action callback, bool isBound = true)
{
this.actionEvent = actionEvent; //actionEvent is either being cloned here, or whenever it's referenced
this.callback = callback;
this.bound = isBound;
if (this.bound)
{
Debug.Log("Binding callback to event!");
this.actionEvent += this.callback; //This is a reference to the plrInput class
}
}
//Bound property binds and unbinds the callback function to the event when changed
public bool Bound
{
get { return bound; }
set
{
if (bound != value)
{
bound = value;
if (bound)
{
Debug.Log("Rebinding callback!");
actionEvent += callback;
return;
}
actionEvent -= callback;
Debug.Log("Unbinding callback!");
}
}
}
}
The class is instantiated in the start method like so:
void Start
{
Binding JumpBinding = new Binding(ref plrInput.OnSpacePressed, Jump);
// plrInput.OnSpacePressed is a delegate from another class which is invoked when I press space
// Jump is a method which causes the player to jump
}
I'm new to c# and I learned about delegates and the ref keyword yesterday, so maybe my problem stems from a misunderstanding. The problem I'm running into is that the class member actionEvent in Binding is just a clone of the actionEvent argument passed through the constructor, even though I pass it by reference. I was able to confirm this through testing.
When I invoke plrInput.OnSpacePressed while the callback is bound to the Binding class member actionEvent, the callback is not being called. Does anyone have an explanation for why I'm getting this behavior, and how I can potentially fix this problem or if there's a better approach?
Related
I am having trouble figuring out how to program delegate method calls across classes in C#. I am coming from the world of Objective-C, which may be confusing me. In Objective-C, I can assign a delegate object inside a child class, to be the parent class (I.e., childViewcontroller.delegate = self;). Then I can to fire a method in the delegate class by using:
if([delegate respondsToSelector:#selector(methodName:)]) {
[delegate methodName:parametersgohere];
}
However, I can't figure out how to do this in C#. I've read a bit about C# delegates in general (for example, here), but I'm still stuck.
Are there any examples that explain this?
Here is my scenario in full:
I have classA which instantiates an instance of classB. ClassB fires a method (which call a web service), and upon response, I'd like to fire a method in classA.
Any 'Hello World' types of tutorials out there that might explain the very basics of this?
A delegate is an object that points to a method, be it a static or instance method. So for your example, you would just use the event model:
class Caller {
public void Call() {
new Callee().DoSomething(this.Callback); // Pass in a delegate of this instance
}
public void Callback() {
Console.WriteLine("Callback called!");
}
}
class Callee {
public void DoSomething(Action callback) {
// Do stuff
callback(); // Call the callback
}
}
...
new Caller().Call(); // Callback called!
The Caller instance passes a delegate to the Callee instance's DoSomething method, which in turn calls the pointed-to method, which is the Callback method of the Caller instance.
In C# what I think you are looking for are called events. They are a language feature that allows a class instance to expose a public delegate in a way that other class instances can subscribe to. Only the exposing class is allowed to raise the event.
In your example:
public class ClassB {
// Note the syntax at the end here- the "(s, e) => { }"
// assigns a no-op listener so that you don't have to
// check the event for null before raising it.
public event EventHandler<MyEventArgs> MyEvent = (s, e) => { }
public void DoMyWork() {
// Do whatever
// Then notify listeners that the event was fired
MyEvent(this, new MyEventArgs(myWorkResult));
}
}
public class ClassA {
public ClassA(ClassB worker) {
// Attach to worker's event
worker.MyEvent += MyEventHandler;
// If you want to detach later, use
// worker.MyEvent -= MyEventHandler;
}
void MyEventHandler(Object sender, MyEventArgs e) {
// This will get fired when B's event is raised
}
}
public class MyEventArgs : EventArgs {
public String MyWorkResult { get; private set; }
public MyEventArgs(String myWorkResult) { MyWorkResult = myWorkResult; }
}
Note that the above will be synchronous. My understanding is that Objective-C delegates are all Actor pattern, so they are asynchronous. To make the above asynch, you'll need to delve into threading (probably want to google "C# Thread pool").
I've got the following class:
public class Terminal : IDisposable
{
readonly List<IListener> _listeners;
public Terminal(IEnumerable<IListener> listeners)
{
_listeners = new List<IListener>(listeners);
}
public void Subscribe(ref Action<string> source)
{
source += Broadcast;
//Store the reference somehow?
}
void Broadcast(string message)
{
foreach (var listener in _listeners) listener.Listen(message);
}
public void Dispose()
{
//Unsubscribe from all the stored sources?
}
}
I've searched for a while and it appears that an argument passed with the ref keyword can't be stored. Trying to add the source argument to a list or to assign it to a field variable doesn't allow it to keep a reference to the actual delegate's original reference; so my questions are:
Is there a way to unsubscribe from all the sources without passing their references again?
If not, how can the class be changed in order to support it, but still maintain the subscription by passing a delegate through a method?
Is it possible to achieve it without using Reflection?
Is it possible to achieve it without wrapping the delegate/event in a class and then passing the class as a parameter for the subscription?
Thank you.
EDIT: It appears that without using a Wrapper or Reflection, there's no solution to the given problem. My intention was to make the class as much portable as possible, without having to wrap delegates in helper classes. Thanks everyone for the contributions.
Edit: Ok, that was a bad idea, so back to the basics:
I recommend creating a wrapper class over an Action:
class ActionWrapper
{
public Action<string> Action;
}
And restructuring your initial class to work with wrappers:
private ActionWrapper localSource;
public void Subscribe(ActionWrapper source)
{
source.Action += Broadcast;
localSource = source;
}
public void Dispose()
{
localSource.Action -= Broadcast;
}
Now you should get the desired results.
public class Terminal : IDisposable
{
List<IListener> _listeners;
List<Action<string>> _sources;
public Terminal(IEnumerable<IListener> listeners)
{
_listeners = new List<IListener>(listeners);
_sources = new List<Action<string>>();
}
public void Subscribe(ref Action<string> source)
{
_sources.Add( source );
source += Broadcast;
}
void Broadcast(string message)
{
foreach (var listener in _listeners) listener.Listen(message);
}
public void Dispose()
{
foreach ( var s in _sources ) s -= Broadcast;
}
}
I would suggest that the subscription method should return an implementation of a SubscriptionHelper class, which implements IDisposable. A simple implementation would be for SubscriptionHelper to hold a reference to the subscription list and a copy of the subscription delegate; the subscription list itself would be a List<SubscriptionHelper>, and the Dispose method for SubscriptionHelper would remove itself from the list. Note that if the same delegate gets subscribed multiple times, each subscription will return a different SubscriptionHelper; calling Dispose on a SubscriptionHelper will cancel the subscription for which it had been returned.
Such an approach would be much cleaner than the Delegate.Combine/Delegate.Remove method used by the normal .net pattern, whose semantics can get very strange if an attempt is made to subscribe and unsubscribe multi-target delegates.
EDIT:
Yep, my bad - delegates are immutable types, so adding a method to an invocation list will actually create a new delegate instance.
Which leads to an answer no to your question. To unsubscribe the delegate you need to remove your Broadcast method from the delegate's invocation list. This means creating a new delegate and assigning it to the original field or variable. But you cannot access the original once you're out of Subscribe method. Plus there can be other copies of that original field/variable that have your method on the invocation list. And there is no way for you to know about all of them and change there values.
I'd suggest to declare an interface with the event for your purpose. This will be quite flexible approach.
public interface IMessageSource
{
event Action<string> OnMessage;
}
public class MessageSource : IMessageSource
{
public event Action<string> OnMessage;
public void Send(string m)
{
if (OnMessage!= null) OnMessage(m);
}
}
public class Terminal : IDisposable
{
private IList<IMessageSource> sources = new List<IMessageSource>();
public void Subscribe(IMessageSource source)
{
source.OnMessage += Broadcast;
sources.Add(source);
}
void Broadcast(string message)
{
Console.WriteLine(message);
}
public void Dispose()
{
foreach (var s in sources) s.OnMessage -= Broadcast;
}
}
Original answer
Is there a particular reason why you pass source delegate as ref? You need this if you, for example, want to return a different delegate from the method.
Otherwise, the delegate is reference type, so you can subscribe to it without passing it as ref...
It's reasonably simple, but there are a few pitfalls. If you store a reference to the source objects, as most of the examples so far have proposed, the object won't be garbage collected. The best way to avoid this is to use an WeakReference, that will allow the GC to work properly.
So, all you have to do is this:
1) Add a list of sources to the class:
private readonly List<WeakReference> _sources = new List<WeakReference>();
2) Add the source to the list:
public void Subscribe(ref Action<string> source)
{
source += Broadcast;
//Store the reference
_sources.Add(new WeakReference(source));
}
3) And then just implement dispose:
public void Dispose()
{
foreach (var r in _sources)
{
var source = (Action<string>) r.Target;
if (source != null)
{
source -= Broadcast;
source = null;
}
}
_sources.Clear();
}
That said, there's also the question of why the Action must be passed as a ref. In the current code, there's no reason for that. Anyway, it doesn't affect the problem or the solution.
Perhaps, instead of trying to store a reference to the delegate, have what calls Subscribe use its reference to the object with the delegate to create actions for the subscription and unsubscription . Its an additional parameter, but its still straightforward.
public void Subscribe(Action<Action<string>> addHandler,Action<Action<string>> removeHandler)
{
//Prevent error for possibly being null in closure
Action<string> onEvent = delegate { };
//Broadcast when the event occurs, unlisten after (you could store onEvent and remove handler yourself)
onEvent = (s) => { Broadcast(s); removeHandler(onEvent); };
addHandler(onEvent);
}
And an example subscribing.
public event Action<string> CallOccured;
public void Program()
{
Subscribe(a => CallOccured += a, a => CallOccured -= a);
CallOccured("Hello");
}
Im trying to specify an event in an interface with custom arguments. I need the event argument to be an object. I've tried to strip the following code down as much as possible. Im currently getting the following error.
ArgumentNullException: Argument cannot be null.
Parameter name: obj
LittleObject.IObject.add_ChangeEvent (System.EventHandler`1 value)
(at LittleObject.cs line : [where the comment is])
Code
public class ChangeEventArgs : EventArgs {
public ChangeEventArgs(SomeClass c){ someClass = c;}
public SomeClass someClass;
}
public interface IObject {
void OnChangeEvent(ChangeEventArgs e);
event EventHandler<ChangeEventArgs> ChangeEvent;
}
public class LittleObject : IObject{
public event EventHandler<ChangeEventArgs> ChangeEvent;
public fireEvent(){
OnChangeEvent(new ChangeEventArgs(new SomeClass()));
}
event EventHandler<ChangeEventArgs> IObject.ChangeEvent{
add{ // error here
lock (ChangeEvent) {
ChangeEvent += value;
}
}
remove{
lock (ChangeEvent){
ChangeEvent -= value;
}
}
}
public void OnChangeEvent(ChangeEventArgs e){
if(ChangeEvent != null) {
ChangeEvent(this, e);
}
}
}
public class Main {
IObject currentObject;
void init(){
currentObject = new IObject();
currentObject.ChangeEvent += new EventHandler<ChangeEventArgs>(OnChangeEvent);
}
void doStuff(){
currentObject.fireEvent();
}
public void OnChangeEvent(object sender, ChangeEventArgs e) {
SomeClass someClass = e.someClass;
}
}
This code is quite messy, but I believe the reason you are getting the exception is because you are locking on a null-reference.
When you do:
add
{
lock (ChangeEvent) { ... }
}
The compiler is actually using the private field backing the ChangeEvent event (see field-like event). Note that the initial value of this field is null (it has not explicitly been assigned an initial value, say through a field-initializer).
Now the first time someone subscribes to the "wrapping" event (someObject.ChangeEvent += ...), your custom add accessor is called, resulting in an attempt to take a lock on the object referred to by that field (the lock actually needs some data in the object-header called a 'sync-block'). Of course, there is no such object, which is what makes the lock go bang.
As for the strange obj parameter, that's the one from Monitor.TryEnter(object obj, ref bool lockTaken), which is what a C# lock statement compiles down to (previous versions of C# targeted a different method).
Honestly though, I would strongly consider redesigning this entire piece of code.
EDIT: Clarified the use of the wrapping event.
I'm trying to use the MVVM pattern in my Silverlight 3 application and am having problems getting binding to a command property of a view model working. First off, I'm trying to add an attached property called ClickCommand, like this:
public static class Command
{
public static readonly DependencyProperty ClickCommandProperty =
DependencyProperty.RegisterAttached(
"ClickCommand", typeof(Command<RoutedEventHandler>),
typeof(Command), null);
public static Command<RoutedEventHandler> GetClickCommand(
DependencyObject target)
{
return target.GetValue(ClickCommandProperty)
as Command<RoutedEventHandler>;
}
public static void SetClickCommand(
DependencyObject target, Command<RoutedEventHandler> value)
{
// Breakpoints here are never reached
var btn = target as ButtonBase;
if (btn != null)
{
var oldValue = GetClickCommand(target);
btn.Click -= oldValue.Action;
target.SetValue(ClickCommandProperty, value);
btn.Click += value.Action;
}
}
}
The generic Command class is a wrapper around a delegate. I'm only wrapping a delegate because I wondered if having a delegate type for a property was the reason things weren't working for me originally. Here's that class:
public class Command<T> /* I'm not allowed to constrain T to a delegate type */
{
public Command(T action)
{
this.Action = action;
}
public T Action { get; set; }
}
Here's how I am using the attached property:
<Button u:Command.ClickCommand="{Binding DoThatThing}" Content="New"/>
The syntax seems to be accepted, and I think that when I tested all of this with a string property type, that worked fine. Here's the view model class that is being bound to:
public class MyViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged = delegate { };
public Command<RoutedEventHandler> DoThatThing
{
get
{
return new Command<RoutedEventHandler>(
(s, e) => Debug.WriteLine("Never output!"));
}
}
}
The delegate contained in the Command property is never invoked. Also, when I place breakpoints in the getter and setter of the attached property, they are never reached.
In trying to isolate the problem, I changing the property type to string; the breakpoint in the getter and setter was also never reached, yet throwing an exception in them did cause the application to terminate, so I am thinking it's a framework eccentricity.
Why is this stuff not working? I also welcome alternate, hopefully simpler ways to bind event handlers to view models.
You have at least two problems here.
First, you are relying on the SetXxx method being executed. The CLR wrappers for dependency properties (the property setter or SetXxx method) are not executed when the DP is set from XAML; rather, WPF sets the value of the internally managed DP "slot" directly. (This also explains why your breakpoints were never hit.) Therefore, your logic for handling changes must always occur in the OnXxxChanged callback, not in the setter; WPF will call that callback for you when the property changes regardless of where that change comes from. Thus (example taken from a slightly different implementation of commands, but should give you the idea):
// Note callback in PropertyMetadata
public static readonly DependencyProperty CommandProperty =
DependencyProperty.RegisterAttached("Command", typeof(ICommand), typeof(Click),
new PropertyMetadata(OnCommandChanged));
// GetXxx and SetXxx wrappers contain boilerplate only
public static ICommand GetCommand(DependencyObject obj)
{
return (ICommand)obj.GetValue(CommandProperty);
}
public static void SetCommand(DependencyObject obj, ICommand value)
{
obj.SetValue(CommandProperty, value);
}
// WPF will call the following when the property is set, even when it's set in XAML
private static void OnCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
ButtonBase button = d as ButtonBase;
if (button != null)
{
// do something with button.Click here
}
}
Second, even with this change, setting ClickCommand on a control that doesn't already have a value set will cause an exception, because oldValue is null and therefore oldValue.Action causes a NullReferenceException. You need to check for this case (you should also check for newValue == null though this is unlikely ever to happen).
Take the following C# class:
c1 {
event EventHandler someEvent;
}
If there are a lot of subscriptions to c1's someEvent event and I want to clear them all, what is the best way to achieve this? Also consider that subscriptions to this event could be/are lambdas/anonymous delegates.
Currently my solution is to add a ResetSubscriptions() method to c1 that sets someEvent to null. I don't know if this has any unseen consequences.
From within the class, you can set the (hidden) variable to null. A null reference is the canonical way of representing an empty invocation list, effectively.
From outside the class, you can't do this - events basically expose "subscribe" and "unsubscribe" and that's it.
It's worth being aware of what field-like events are actually doing - they're creating a variable and an event at the same time. Within the class, you end up referencing the variable. From outside, you reference the event.
See my article on events and delegates for more information.
Add a method to c1 that will set 'someEvent' to null.
public class c1
{
event EventHandler someEvent;
public ResetSubscriptions() => someEvent = null;
}
class c1
{
event EventHandler someEvent;
ResetSubscriptions() => someEvent = delegate { };
}
It is better to use delegate { } than null to avoid the null ref exception.
The best practice to clear all subscribers is to set the someEvent to null by adding another public method if you want to expose this functionality to outside. This has no unseen consequences. The precondition is to remember to declare SomeEvent with the keyword 'event'.
Please see the book - C# 4.0 in the nutshell, page 125.
Some one here proposed to use Delegate.RemoveAll method. If you use it, the sample code could follow the below form. But it is really stupid. Why not just SomeEvent=null inside the ClearSubscribers() function?
public void ClearSubscribers ()
{
SomeEvent = (EventHandler) Delegate.RemoveAll(SomeEvent, SomeEvent);
// Then you will find SomeEvent is set to null.
}
Setting the event to null inside the class works. When you dispose a class you should always set the event to null, the GC has problems with events and may not clean up the disposed class if it has dangling events.
You can achieve this by using the Delegate.Remove or Delegate.RemoveAll methods.
Conceptual extended boring comment.
I rather use the word "event handler" instead of "event" or "delegate". And used the word "event" for other stuff. In some programming languages (VB.NET, Object Pascal, Objective-C), "event" is called a "message" or "signal", and even have a "message" keyword, and specific sugar syntax.
const
WM_Paint = 998; // <-- "question" can be done by several talkers
WM_Clear = 546;
type
MyWindowClass = class(Window)
procedure NotEventHandlerMethod_1;
procedure NotEventHandlerMethod_17;
procedure DoPaintEventHandler; message WM_Paint; // <-- "answer" by this listener
procedure DoClearEventHandler; message WM_Clear;
end;
And, in order to respond to that "message", a "event handler" respond, whether is a single delegate or multiple delegates.
Summary:
"Event" is the "question", "event handler (s)" are the answer (s).
Remove all events, assume the event is an "Action" type:
Delegate[] dary = TermCheckScore.GetInvocationList();
if ( dary != null )
{
foreach ( Delegate del in dary )
{
TermCheckScore -= ( Action ) del;
}
}
This is my solution:
public class Foo : IDisposable
{
private event EventHandler _statusChanged;
public event EventHandler StatusChanged
{
add
{
_statusChanged += value;
}
remove
{
_statusChanged -= value;
}
}
public void Dispose()
{
_statusChanged = null;
}
}
You need to call Dispose() or use using(new Foo()){/*...*/} pattern to unsubscribe all members of invocation list.
Instead of adding and removing callbacks manually and having a bunch of delegate types declared everywhere:
// The hard way
public delegate void ObjectCallback(ObjectType broadcaster);
public class Object
{
public event ObjectCallback m_ObjectCallback;
void SetupListener()
{
ObjectCallback callback = null;
callback = (ObjectType broadcaster) =>
{
// one time logic here
broadcaster.m_ObjectCallback -= callback;
};
m_ObjectCallback += callback;
}
void BroadcastEvent()
{
m_ObjectCallback?.Invoke(this);
}
}
You could try this generic approach:
public class Object
{
public Broadcast<Object> m_EventToBroadcast = new Broadcast<Object>();
void SetupListener()
{
m_EventToBroadcast.SubscribeOnce((ObjectType broadcaster) => {
// one time logic here
});
}
~Object()
{
m_EventToBroadcast.Dispose();
m_EventToBroadcast = null;
}
void BroadcastEvent()
{
m_EventToBroadcast.Broadcast(this);
}
}
public delegate void ObjectDelegate<T>(T broadcaster);
public class Broadcast<T> : IDisposable
{
private event ObjectDelegate<T> m_Event;
private List<ObjectDelegate<T>> m_SingleSubscribers = new List<ObjectDelegate<T>>();
~Broadcast()
{
Dispose();
}
public void Dispose()
{
Clear();
System.GC.SuppressFinalize(this);
}
public void Clear()
{
m_SingleSubscribers.Clear();
m_Event = delegate { };
}
// add a one shot to this delegate that is removed after first broadcast
public void SubscribeOnce(ObjectDelegate<T> del)
{
m_Event += del;
m_SingleSubscribers.Add(del);
}
// add a recurring delegate that gets called each time
public void Subscribe(ObjectDelegate<T> del)
{
m_Event += del;
}
public void Unsubscribe(ObjectDelegate<T> del)
{
m_Event -= del;
}
public void Broadcast(T broadcaster)
{
m_Event?.Invoke(broadcaster);
for (int i = 0; i < m_SingleSubscribers.Count; ++i)
{
Unsubscribe(m_SingleSubscribers[i]);
}
m_SingleSubscribers.Clear();
}
}