Is it considered a bad practice when someone performs complicated calculations in an event handler?
Does a calculation-cl开发者_运维百科uttered .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)
精彩评论