c# how to modify parameter that is passing through a delegate - c#

I have the following delegate
System.Action<SomeMessage> TheDelegate;
Which has a couple subscribers, however as the message gets passed through all the subscribers, each subscriber will do something to it and that change persists and gets passed to the next subscriber, which is something that I don't want.
Is there a way that I can use the original message as the parameter for all subscribers?
Edit:
SomeMessage is a class, thus it gets passed by reference through the subscribers

To name two possibilities:
Clone the message each time it is passed to a subscriber. How is the message structured, is it cheap to clone? Maybe you could even pass it as struct? Cloning could be done by implementing ICloneable, clone on a per-property basis, which can be automated by a framework, e.g, Automapper (http://automapper.org) or, if you mess around with some JSON Lib like JSON.NET, you could do something like var clone = FromJson(ToJson(original)). This is surely not a fast approach but an easy one that works well with deep objects.
Another way would be making the message itself immutable and let each subscriber pass change requests to some kind of collector, e.g.
like this:
interface ICommandSequence
{
void AddCommand(ICommand);
}
and the Action becomes
System.Action<ImmutableMessage, ICommandSequence>
Each subscriber could now pass command instances to the ICommandSequence instance. And after all subscribers have been called, you could execute the command sequence, and apply changes to message objects. How the commands look depends on the way your messages and message processing looks.
If your application cares about a design that is strongly focused on the business domain, you could build commands that represent real-world business events, as it is done in CQRS, for example.

Related

How to store generic Actions with different parameters in a Dictionary?

I want to store delegates(Action) with one generic parameter in a Dictionary and I would like to avoid any Code Smell
regarding to down/up-casting if that is possible at all.
Basically I am implementing some kind of a Request/Response Callback manager where the user requests something from a
REST API and provides me a callback with the correct Response object. In a nutshell the method the user calls looks like that:
void GetUser(int id, Action<GetUserResponse> callback);
I then, sent out the request and save the callback into my "Callback Manager". When the response from the server
comes in (mostly json) I parse it into a GetUserResponse object and fire the callback. However there are many different
Requests which have different response objects and the Callback Manager has to prioritize them (and also some other stuff)
Instead of having a Dictionary for every single request which stores the callbacks of that request, I would like to
have a single Dictionary which stores all of the callbacks (and a unique id).
Basically something like this: (which obviously does not work like that)
Dictionary<GUID,Action<T>> AllCallbacks;
Is that possible without having to cast anything on the "user side"?
Have a look at Dictionary of Action<T> Delegates.
Should give you some guidance of options available to you. I don't think there is a simple and elegant solution out of the box.
You could use Dictionary<GUID,Action<dynamic>> AllCallbacks; but then you would need to type check and cast accordingly.

How do I push an entity onto an Rx Observable?

I have a class that is going to be responsible for generating events on an frequent but irregular interval, that other classes must consume and operate on. I want to use Reactive Extensions for this task.
The consumer side of this is very straightforward; I have my consumer class implementing IObserver<Payload> and all seems well. The problem comes on the producer class.
Implementing IObservable<Payload> directly (that is, putting my own implementation for IDisposable Subscribe(IObserver<Payload> ) is, according to the documentation, not recommended. It suggests instead composing with the Observable.Create() set of functions. Since my class will run for a long time, I've tried creating an Observable with var myObservable = Observable.Never(), and then, when I have new Payloads available, calling myObservable.Publish(payloadData). When I do this, though, I don't seem to hit the OnNext implementation in my consumer.
I think, as a work-around, I can create an event in my class, and then create the Observable using the FromEvent function, but this seems like an overly complicated approach (i.e., it seems weird that the new hotness of Observables 'requires' events to work). Is there a simple approach I'm overlooking here? What's the 'standard' way to create your own Observable sources?
Create a new Subject<Payload> and call it's OnNext method to send an event. You can Subscribe to the subject with your observer.
The use of Subjects is often debated. For a thorough discussion on the use of Subjects (which links to a primer), see here - but in summary, this use case sounds valid (i.e. it probably meets the local + hot criteria).
As an aside, overloads of Subscribe accepting delegates may remove the need for you to provide an implemention of IObserver<T>.
Observable.Never() doesn't "send" notifications, you should use Observable.Return(yourValue)
If you need a guide with concrete examples i recommend reading Intro to Rx
Unless I come across a better way of doing it, what I've settled on for now is the use of a BlockingCollection.
var _itemsToSend = new BlockingCollection<Payload>();
IObservable<MessageQueuePayload> _deliverer =
_itemsToSend.GetConsumingEnumerable().ToObservable(Scheduler.Default);

Auto Generate Custom Events at runtime

I have a class that Handles send & receive over a socket between my application and the network. This class uses other classes, including a low level sockket connection class and a PDU handler class that creates the messages to send and handles received data.
Now i use an event to signal my class that the low level connection class has data for it and i need to send that data to the PDU handler to convert to information the application can use and then hand the data to the application.
For future usage, i am trying to get the class to be as generic as possible, so that on future Server/Client projects i will need only to change the PDU handler to take under consideration the new operations availlable and how to handle the data.
All that is well underway and now i am facing the isssue of handing the data back to the app. For that, my logical approach is an event letting the app know data is ready for collection. For that i can either:
a) have one event and let the app sort out what kind of message it is through the operation code (doable)
b) Have one event per operation code and have the app subscribe to all of them and thus know at start what it is getting
Considering the idea of making things generic, and the approach stated in b, is there a way to dinamicly create events based on a given delegate signature at runtime?
e. g.
imagine you have opcodes in an enum called MyOperation1 and MyOperation2 and you have defined a delegate like:
public delegate void PDUEventHandler(ParamType Param, [...]);
and i want to define events called:
public event PDUEventHandler MyOperation1;
public event PDUEventHandler MyOperation2;
But if i add a new operation code i will need an event for it.
Can this events be created dinamicly or do i need to do it by hand?
If i need to do it by hand then i guess a single event would be better and handle things app side.
Perhaps what you need is a callback - essentially you pass to the event handler a delegate for it to execute when the handler is done. Here's a stackoverflow thread to give you an idea
In terms of event handlers & re-useability, perhaps you can extend EventArgs and have that delegate as a property.
EDIT:
I was thinking a single PDUEventHandler having common code and a "hole" where custom code is run. That custom code is passed to the handler as a delegate (i.e. a method) or even a class instance. But let's change that a little...
Sounds like you need a factory. In fact you're practically describing a factory.
Conceptually let go of the idea of passing special opcodes to an EventHandler per se, or having multi-signature PDUEventHandlers.
Create a PDUHandlerFactoryclass. The factory returns a customized instance as a general PDUHandler class reference. Then instead of a PDUEventHander you caller has a PDUHandler reference that points to the factory-custom instance.

Misuse of Observer Pattern?

I have a Car object which contains a latitude field and a longitude field. I use the observer pattern so that any time either of these fields change in my application, my car object is notified.
I now find the need to create several other car objects whose default values I wish to have the same as what is the current latitude and the current longitude. I can keep this state in my Notifier object and when a new observer (the new car) registers to listen I can re-broadcast out the values so the new listener will be up to date.
Is this a misuse of the observer pattern, i.e bad design?
The only thing that strikes me as dangerous about this approach is that it's easy to code your observers to assume that if they get a notification, something has changed. With the setup you have above, that's no longer true. Therefore your observers will have to check that something truly changed if they are supposed to perform any actions when they receive a notification.
Probably common sense, but also an easy oversight if you're modifying existing code.
I think this is a textbook example of good use of the Observer Pattern.
Of course, there may be some aspect of this that you have misgivings about. If you explain what your concerns are these could be better discussed.
It would be better if your subject (the object which knows the current latitude and longitude) also exposes a getter method. Any new listener (a new car in your example), right after registration, might get the current values (lat/long) and be informed through the broadcast of any change thereafter. This will avoid needlessly notifying already registered listeners.
Consider that in a common variation of the observer pattern, the subject notifies the listeners that a change has happened, and the listeners then actively query the current value from the subject (hence the need of a getter method).
An Observer pattern is used in one to many relationship. When you want to notify multiple objects, when one object changes state. Your case is a many to one. I believe its a misuse (I may be wrong). Obvious impact is complexity of code. But the side effect could be loss of flexibility. Look at it like this, what changes. If you want to add more Car's you can, without changing the notification receiver. The receiver need now know about your new Car's implementation. All it cares about is the state.
Now, what happens when you want to add more receivers, which will be the most probable case (requirements not thought through :)). In this case all your car objects will need a change to refer to a new receiver.

C# Best practice: Centralised event controller or not

I have an app which consists of several different assemblies, one of which holds the various interfaces which the classes obey, and by which the classes communicate across assembly boundaries. There are several classes firing events, and several which are interested in these events.
My question is as follows: is it good practice to implement a central EventConsolidator of some kind? This would be highly coupled, as it would need to know every class (or at least interface) throwing an event, and every consumer of an event would need to have a reference to EventConsolidator in order to subscribe.
Currently I have the situation where class A knows class B (but not C), class B knows class C, etc. Then if C fires an event B needs to pick it up and fire its own event in order for A to respond. These kinds of chains can get quite long, and it may be that B is only interested in the event in order to pass it along. I don't want A to know about C though, as that would break encapsulation.
What is good practice in this situation? Centralise the events, or grin and bear it and define events in each intermediate class? Or what are the criteria by which to make the decision? Thanks!
Edit: Here is another question asking essentially the same thing.
You could put the event itself in an interface, so that A didn't need to know about C directly, but only that it has the relevant event. However, perhaps you mean that the instance of A doesn't have sight of an instance of C...
I would try to steer clear of a centralised event system. It's likely to make testing harder, and introduced tight coupling as you said.
One pattern which is worth knowing about is making event proxying simple. If B only exposes an event to proxy it to C, you can do:
public event FooHandler Foo
{
add
{
c.Foo += value;
}
remove
{
c.Foo -= value;
}
}
That way it's proxying the subscription/unsubscription rather than the act of raising the event. This has an impact on GC eligibility, of course - which may be beneficial or not, depending on the situation. Worth thinking about though.
What you could try is using the event brokering of either NInject or the Unity Application Block.
This allows you to, for example:
[Publish("foo://happened")]
public event EventHandler<FooArgs> FooHappened;
[Subscribe("foo://happened")]
public void Foo_Happened(object sender, FooArgs args)
{ }
If both objects are created through the container the events will be hooked up automatically.
I'd probably try to massage the domain so that each class can directly depend on the appropriate event source. What I mean is asking the question why don't A know about C? Is there perhaps a D waiting to emerge?
As an alternative approach you could consider an event broker architecture. It means observers don't know directly about the source. Here's an interesting video.
This would be highly coupled, as it would need to know every class
I think you answered your own question if you consider that coupling is bad! Passing events through a chain of potential handlers is a fairly common pattern in many environments; It may not be the most efficient approach, but it avoids the complexity that your suggested approach would involve.
Another approach you could take is to use a message dispatcher. This involves using a common message format (or at least a common message header format) to represent events, and then placing those messages into a queue. A dispatcher then picks up each of those events in turn (or based on some prioritisation), and routes them directly to the required handler. Each handler must be registered with the dispatcher at startup.
A message in this case could simply be a class with a few specific fields at the start. The specific message could simply be a derivative, or you could pass your message-specific data as an 'object' parameter along with the message header.
You can check out the EventBroker object in the M$ patterns and practises lib if you want centralised events.
Personally I think its better to think about your architecture instead and even though we use the EventBroker here, none of our new code uses it and we're hoping to phase it out one sunny day.
we have our own event broker implementation (open source)
Tutorial at: http://sourceforge.net/apps/mediawiki/bbvcommon/index.php?title=Event_Broker
And a performance analysis at: www.planetgeek.ch/2009/07/12/event-broker-performance/
Advantages compared to CAB:
- better logging
- extension support
- better error handling
- extendable handlers (UI, Background Thread, ...)
and some more I cannot recall right now.
Cheers,
Urs

Categories