I'm dealing with an C# Windows Forms application. I have some forms and all these forms are sensitive to the value of a global variable. [Static Member Of A Static Class]
I don't want to run a timer on every form and check this variable. I want these forms to be sensitive to the value of this variable and each form to perform its own routine.
What should I do? Is there a standard way to implement these types of algorithms?
It's a normal situation. Sometimes we need to use something like timers. (This is called Polling method). Sometimes we need Interrupts (This is called Event
in the C#
terminology).
So. As you said we have an static class:
internal static class StaticClass
{
public delegate void SomethingHappendEventHandler(object sender, EventPayload e);
public static event SomethingHappendEventHandler SomethingHappendEvent;
public class EventPayload
{
public string Message { get; set; }
}
public static async Task BroadcastAnEvent(string message)
{
SomethingHappendEvent?.Invoke(null, new EventPayload()
{
Message = message
// Extra info should be defined in payload class if you want to pass them.
});
}
}
and we have some Form
s that wanna catch those Event
s. for every single form you should do this:
public ChildForm()
{
InitializeComponent();
StaticClass.SomethingHappendEvent += StaticClass_SomethingHappendEvent;
}
private void StaticClass_SomethingHappendEvent(object sender, StaticClass.EventPayload e)
{
MessageBox.Show(e.Message);
}
You can call:
StaticClass.BroadcastAnEvent("My message");
Wherever you want and all of these forms will catch this message and they are able to use it.