I have a .NET 1.1. application which provides string resources through a bespoke translation system that looks a little like this:
interface ITranslationProvider
{
string GetTranslation(string key);
event LanguageChangedEvent LanguageChanged;
}
ie: language can change at runtime, and components need to respond by updating display strings.
A single translation provider lasts the lifetime of the application, whereas Windows Forms components that consume translation services get created dynamically. If I write forms components that use this, when is the correct time to unsubscribe from the LanguageChanged event?
for example, it seems like overriding Disposing() should work:
class MyPanel : System.Windows.Forms.Panel
{
public MyPanel(ITranslationProvider translator)
{
this.translator = translator;
translator.LanguageChanged += new LanguageChangedEvent(SetText);
SetText();
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
// is this the correct place to unregister? will Dispose() get
// called on this panel, even though the translator's event has
// a reference to it?
translator.LanguageChanged -= new LanguageChangedEvent(SetText);
}
private void SetText()
{
this.Text = translator.GetTranslation("my.panel.text");
}
private ITranslationProvider translator;
}
… but I can’t find a definitive answer to whether this is safe or not. Any ideas?
Your control will be
Disposed when its parent form is disposed.If you show the form by calling
Show(), .Net will automatically dispose it when it’s closed.If you call
ShowDialog(), you are responsible for disposing the form, presumably in ausingblock. (You should dispose the form in any case, even if it doesn’t add event handlers)