27 Şubat 2020 Perşembe

EventHandler Sınıfı

Giriş
Bu sınıf ile ilgili bazı eleştiriler şöyle.
C# Events/Eventhandlers are:

-blocking
-throwing Exceptions
-sequential
-deterministic executed in order
-MulticastDelegates
-a handler is always dependent on the behavior of the handlers registered earlier

Actually they are pretty close to regular function pointers. Despite beeing a sequence of them.

If any event-subscriber is doing evil things (blocking, throwing Exceptions):

-the event invoker is blocked (in the worst case indefinitely)
-the event invoker has to deal with unpredictable exceptions
-the internal sequential eventhandler calling will break at the first exception
-any EventHandler internally stored after the failing Eventhandler will not be executed
Örnek
Şöyle yaparız
public class LocationChangedEventArgs : EventArgs
{
  ...
}

public class Mediator 
{
  public event EventHandler<LocationChangedEventArgs> LocationChanged;

  public void OnLocationChanged(object sender,LocationChangedEventArgs locationInfo) 
  {
    LocationChanged?.Invoke(sender,locationInfo;
  }
}

Mediator.Instance.OnLocationChanged(this,new LocationChangedEventArgs{...});

Mediator.Instance.LocationChanged += (s,e) => {...}

Hiç yorum yok:

Yorum Gönder