There is an option to use a singleton class. The following is a simple working example done in a windows form app.
using System;
namespace SingletonExamples
{
public sealed class ApplicationJobs
{
private static readonly Lazy<ApplicationJobs> Lazy = new(()
=> new ApplicationJobs());
public delegate void OnValueChanged(int value);
/// <summary>
/// Notify any listeners that <see cref="Value"/> has changed
/// </summary>
public static event OnValueChanged ValueChanged;
/// <summary>
/// Entry point
/// </summary>
public static ApplicationJobs Instance => Lazy.Value;
public int Value { get; set; }
public void Work()
{
for (int index = 0; index < 5; index++)
{
Value += 1;
}
ValueChanged?.Invoke(Value);
}
/// <summary>
/// Increment <see cref="Value"/> by increaseBy
/// which defaults to one if no value is passed
/// </summary>
/// <param name="increaseBy"></param>
public void IncrementValue(int increaseBy = 1)
{
Value += increaseBy;
ValueChanged?.Invoke(Value);
}
/// <summary>
/// This is needed when there are many things to
/// reset
/// </summary>
public void Reset()
{
Value = 0;
ValueChanged?.Invoke(Value);
}
private ApplicationJobs()
{
// TODO any initialization that may be needed
}
}
}
Form code
using System.Windows.Forms;
namespace SingletonExamples
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
ApplicationJobs.ValueChanged += ApplicationSettingsOnValueChanged;
ApplicationJobs.Instance.IncrementValue();
}
private void ApplicationSettingsOnValueChanged(int value)
{
textBox1.Text = ApplicationJobs.Instance.Value.ToString();
}
private void ExecuteButton_Click(object sender, System.EventArgs e)
{
ApplicationJobs.Instance.Work();
}
private void IncrementButton_Click(object sender, System.EventArgs e)
{
ApplicationJobs.Instance.IncrementValue(2);
}
private void ResetButton_Click(object sender, System.EventArgs e)
{
ApplicationJobs.Instance.Reset();
}
}
}