When to use custom c# events - c#

When is it appropriate to raise an event in C#?
As an example, in our system we have data objects being sent to us, say 50 per minute, from an external system. Upon receiving a data packet, we need to have it processed by another object. Would an event or a simple method call be better to use in this situation?
An event seems like a natural fit intuitively, but I'm not clear as to what advantage this may offer as compared to simply using a regular method call.

Events should be used when it is inappropriate for the code which originates the action to have direct knowledge of the code(s) which react to that action.
On one hand, an event does sound appropriate here, because the code which handles data reception should not be dependent on the implementation of the code which does something with said data. Otherwise the data reception code is now responsible for two things - receiving the data and delegating the processing of it.
On the other hand, if the particular processing of the data is directly tied to act of it being sent by the external caller, it may make more sense to make it a function call. We don't really have enough information in your question to say for sure.

IMO using a Queue would be an appropriate first step. Code processing the Queue can in turn either raise events or accept a delegate which performs different tasks based on the kind of data object. Action or Func should work well here.
Remember that when you use events, you have to ensure that handlers get unregistered in a timely manner or else you could have leaks.

In this case an event doesn't make sense. Events tend to be to inform about what is going on, not to replace function calls. They are more informative.
So, you may want to pass in an Action<> function, so that you can then call the function that was passed in, to do the processing.
This would be better than a function call, IMO.
You can look at this page for an example:
http://www.claassen.net/geek/blog/2007/12/action-func-never-write-another.html
Update: If you are not using C#3 then you may want to use a delegate instead, which, an event handler is a specialized delegate.

Related

How to handle an exception in an event?

So - I have this external assembly that I'm using. It fires an event DataReceived. Then I'm doing some database operations which may fail due to problems with the data or because of some errors in the code. It would be great if I could "bubble up" the exception into the GUI. In my case I would need a blocking call to the GUI because of the way the assembly works. I'm not sure if this is a good idea but right now that's the only thing that comes to mind based on how the external code works.
The assembly assumes that if the callback (the event) returned safely then the data was processed succesfully - which may not be the case. Of course I would have to deal with the error in some way but that would mean that the server on the other side would always assume that the data was handled correctly.
My questions are:
Can I throw the exception into the GUI? If so, how?
How can I handle the exception in my event so that the assembly doesn't think I processed the data? Do I need some kind of blocking call/exception into the GUI? (Is this even possible?)
On a side note: Isn't that assembly broken by design somehow? Why would it automatically assume that everything went fine just based on if the callback returned?
I don't think that this is broken by design. If you receive the event you'll get informed that something has changed in the source. Now you should only do what is needed to get the informations you need from the source and do any further processing decoupled from the source. For that purpose I would within the event handler simply grab the data (maybe from the source; maybe from the event args) and put them into a ConcurrentQueue. Within my class another Task is running that using the BlockingCollection the retrieve the elements out of this queue to process them. If anything fails, simply call Invoke() to the gui thread and inform the user about what happened.
Ah, and another approach instead of using ConcurrentQueue would be to use Rx. With that you can subscribe to an event and observe it on a different thread by using ObserveOn() which would lead to nearly the same (in this case) but using a more LINQish syntax.

Awaiting Javascript callback while in constructor of c# object

My object in C# will call some JavaScript when constructed through the webbrowser control. The JavaScript will then call back to our c# code with a success or failure. I need to have the constructor of the C# object wait until the JavaScript returns the callback before it leaves the constructor. How would I go about doing this?
Essentially, I need to make sure that the object will always be properly initialized when created. This is dependent on the javascript calling back, which is at least slightly variable.
While you cannot use async/await in a constructor, it still may be possible to make async JavaScript call-outs and wait for their completion, depending on what you actually do in JavaScript and inside the callback from JavaScript to C# . It's done by organizing a nested message loop, here's an example taking this approach. Note, this may be dangerous as it may lead to code reentrancy.
That said, you still might be able to refactor your code to use async/await with one of the approaches described by Stephen Cleary in his blog entry.
Instead of having an async constructor (which is not possible with .NET, anyway (thanks Servy) (and I don't think any other framework that allows for that is a sane framework, if such a thing exists)), you should:
Construct your object in such a way that you don't depend on that Javascript call;
Call whatever logic you need that will be done past .NET boundaries, and when the Javascript is done and responds...
... Call some initialize() method (name it like that or something similar).
You could have a flag in each instance telling whether is has already passed through the post-Javascript initialization, and some logic in your class so that its instances can only be considered to be in a valid, ready, usable state after that initialization step. Good luck and happy coding :)

IObservable REST Client

I want to write a library that would communicate with a web server and expose data from it to the rest of the world. The web server is nothing special, it exposes several REST methods, mostly GET and POST.
Since I am relatively new to Reactive Extensions (but I love it already) I ask for advice. I decided that the interfaces of the library would expose IObservables. But I dont know how exactly to implement this. I'm thinking I have several options:
1) Expose IObservable<IEnumerable<T>>. Makes sense, REST service returns all requested data at once. User calls Subscribe(), only one IEnumerable is pushed, OnDone is called. So Subscribe() would need to be called multiple times.
2) Expose IObservable<T>. Could be a good choice in some cases I guess. Subscribe() would only be called once, to get other data, there would be methods Refresh() or NextPage() (...) to get more data to the stream. (then instead of IObservable<T> GetResource... it could be a property, IObservable<T> Resource { get; }
3) Forget Rx, do it old fashioned way via events (worst possible thing IMO)
4) Some other way?
Anyone with experience in this area? What I am concerned about is Refreshing (asking for new data), Paging, combining the results and generally having a good maintainable design.
Thx for any advice
I would suggest using the following interface:
public interface IRestService
{
IObservable<T> GetResources<T>();
}
There are a number of reasons behind this choice.
To expose an IObservable<IEnumerable<T>> mixes reactives with interactives (or observables with enumerables) and would force your queries to call .ToObservable() or, even worse, .ToEnumerable() to construct a basic SelectMany query. It's better for you to better to keep your queries and subscribing code nice an clean.
Now, you suggested that with an IObservable<T> you would only subscribe once and you would require a Refresh or NextPage call to get more data to the stream. That's not a good idea. You should instead think of a single subscription would return all the results of a single REST call and then call OnComplete. If you want to invoke a new REST call then just subscribe again.
Further, the semantics of a single subscription call are not clearly expressed in the code. So you need to think about maintaining your code. When you look at the code in the future what are you likely to think that the semantics are? I would suggest that the semantics of a a single subscription would map to a single REST call would be more likely. Your code would have the potential of being more confusing otherwise.
Even further, you should avoid a single subscription model because if any exception is thrown then your observable is done and, of course, calling web services can be very error prone. If you have an error with a multiple subscription model you can recover more easily.
I would also avoid IObservable<T> Resources { get; } because it suggests some sort of "fixed" value where instead it is more dynamic - in other words each call may give you different values. It is better to call a GetResources method rather than a Resources property.
Some, bottom-line, I'd have a IObservable<T> that abstracts a single call to your underlying REST service.
You're combining two concerns here which really should be addressed separately.
The first is your code going and getting data from other sources. The second is publishing that data to interested parties when there is new data available.
In regards to the first, the Reactive Extensions aren't going to help. Your concern here is to get the data on a timed interval; it has to be a timed interval because when making calls to REST services in your code, there's no callback, there's nothing for you to hook into that the service can call.
If there was some sort of callback into your code from the external service, then that could be wrapped in some IObservable<T> implementation which you could then subscribe to and perform your operations on (just forwarding the subscription, really).
The only way you could use the Reactive Extensions for the first concern is to set off a timer by using the static Timer method on the Observable class.
For the second concern (after you have your data and you want to notify subscribers), you absolutely can and should use an IObservable<T> implementation to notify subscribers.
In this case, I strongly recommend that you don't try and deviate from the intent of the Subscribe method on the IObservable<T> interface. You should expose a method that will give you the IObservable<T> that anyone can subscribe to (whether or not the IObservable<T> is hot or cold before Subscribe is called is up to you) and unsubscribe from by calling the Dispose method on the IDisposable interface implementation returned from the call to Subscribe.
That way, your clients can get the IObservable<T>, subscribe for the notifications they want, and then unsubscribe when they're done.

Is it advisable to perform complicated calculations in an event handler?

Is it considered a bad practice when someone performs complicated calculations in an event handler?
Does a calculation-cluttered .OnResize event handler has performance penalties?
If so how to make your way around them? (especially the .Print event, since thats what draws on e.Graphics)
It is not considered bad, not as such.
If your code feels cluttered, clean it up - refactor it.
Unless the event handler should be fast (say a Paint event handler), there is no problem in having it do lots of work.
If you have very intensive calculations to do and still need to have a responsive UI, you need to run the calculations on a separate thread.
I think you mean Paint event, not Print. It's not recommended when you need smooth GUI user interaction: the risk is you can steal CPU time from GUI thread and the app will appear sluggish and unresponsive. If these calculations are really a problem for user interaction, the way out is doing calculations on a separate thread, calculating results in advance and storing them in a separate buffer.
Generally, do not keep a lot of calculations inside an event handler. In event handler call, callbacks are called one by one and if one of the callbacks throws an exception then other callbacks do not receive the event. Post the calculation to a thread so that other callbacks are not affected.
Events are usually used in an event-driven system, usually one driven by the user or where a user is involved. As such, it's a good idea to keep processing short and sweet.
Sometimes, events are called in order to do some processing - apply formatting, prompt the user, provide a chance for the calling code to 'customise' what's going on. This is similar to the strategy pattern (http://en.wikipedia.org/wiki/Strategy_pattern).
To take it a step further, the strategy pattern is a good way of having a contract with the user about how they can have their say about how a process is supposed to happen. For example:
Let's say you're writing a grid control, where the user can dictate formatting for each cell. With events:
User must subscribe to the FormatCell event
With something closer to a strategy pattern:
User must create a class implementing ICellFormatter, with a FormatCell method, and pass that to the grid control - via a property, constructor parameter, etc.
You can see that the event route is 'easier' for the user. But personally I prefer the second method every time - you're creating a clear-cut class whose job it is to deal with cell formatting. It also seems more obvious to me in that case that the FormatCell method could perform some degree of processing; rather than using an Event to perform some task, which seems a bit of lazy design. (Paint is an "event"?.. not really, it's something requested of your code)

Is the callBack method called before the assignment or after here?

I have the code below which is basically calling a Domain Service in a SilverLight Application.
LoadOperation<tCity> loadOperation = _dataContext.Load(query,callBack, true);
Can you tell me which operation is done first?
Is the callBack method called before loadOperation variable is assigned or after it is assigned?
Thanks
Assuming it's meant to be an asynchronous operation, it could happen either way, in theory. The asynchronous operation should occur in another thread, and if that finishes before Load returns, the callback could be called before the assignment completes.
In practice, I'd expect the async call to take much longer than whatever housekeeping Load does at the end of the method - but I also wouldn't put that assumption into the code. Unless there's explicit synchronization to ensure that the assignment occurs before the callback, I don't think it's a good idea to rely on it.
Even if at the moment the assignment always happens first, consider:
What happens if there's no network connection at the moment? The async call could fail very quickly.
What happens if some caching is added client-side? The call could succeed very quickly.
I don't know what kind of testing you're able to do against the RIA services, but sometimes you may want to be able to mock asynchronous calls by making them execute the callback on the same thread - which means the callback could happen in tests before the assignment. You could avoid this by forcing a genuinely asynchronous mock call, but handling threading in tests can get hairy; sometimes it's easiest just to make everything synchronous.
EDIT: I've been thinking about this more, and trying to work out the reasons behind my gut feeling that you shouldn't make this assumption, even though it's almost always going to be fine in reality.
Relying on the order of operations is against the spirit of asynchronicity.
You should (IMO) be setting something off, and be ready for it to come back at any time. That's how you should be thinking about it. Once you start down the slippery slope of "I'm sure I'll be able to just do a little bit of work before the response is returned" you end up in a world of uncertainty.
First, I would say write your callback without any assumptions. But aside from that I don't see how the callback could possibly occur before the assignment. The load operation would have to return immediately after the thread is spun.
There are 3 possible answers to this very specific RIA Services question:
It returns the assignment before the callback.
It may be possible for the callback to occur before the assignment.
You do not care.
Case 1:
Based on a .Net Reflector investigation of the actual load method in question, it appears impossible for it to call the callback before the return occurs. (If anyone wants to argue that they are welcome to explain the intricacies of spinning up background threads).
Case 2:
Proof that "the sky is falling" is possible would have to be shown in the reflected code. (If anyone wants to support this they are also welcome to explain the intricacies of spinning up background threads).
Case 3:
In reality, the return value of a RIA Services load method is normally used to assign a lazy loading data source. It is not used by the callback. The callback is passed its own context, of the loaded data, as a parameter.
StackOverflow is all about practical code answers, so the only practical answer is option 3:
You do not care (as you do/should not use the assignment value from the callback).

Categories