Do you need to remove an event handler in the destructor?

后端 未结 9 1064
情书的邮戳
情书的邮戳 2021-01-31 01:22

I use some UserControls which get created and destroyed within my application during runtime (by creating and closing subwindows with these controls inside).
It

9条回答
  •  逝去的感伤
    2021-01-31 01:57

    WPF doesn't support IDisposable well. If you're implementing a WPF control that needs cleanup, you should think about hooking into the Loaded and Unloaded events instead (or in addition).

    I.e. you connect to the event in the Loaded handler and disconnect in the Unloaded handler. Of course this is only an option if your control does not need to receive the event while it's not "loaded" and if you can correctly support many load/unload cycles.

    The advantage of using the Loaded/Unloaded events is that you don't have to manually dispose the user control everywhere it's used. You should however be aware that the Unloaded event is not fired after application shutdown has begun. E.g. if your shutdown mode is OnMainWindowClose, the Unloaded events for other windows will not be fired. This usually isn't a problem though. It just means that you cannot do stuff reliably in an Unloaded that must happen before/while the application terminates.

提交回复
热议问题