Search code examples
c#timer

multithreading and timer withing singleton


I implement a class with singleton like this

        public static SingleToneClass Instance
        {
            get
            {
                return Lazy.Value;
            }
        }
private static readonly Lazy<SingleToneClass > Lazy = new Lazy<SingleToneClass >(() => new RABTProxy());

within SingleToneClass there's a System.Timers timer

while trying to access the class from different threads the timer suddenly stop any idea how to fix something like this , this is a sample of what am testing

 class Program
{
    static void Main(string[] args)
    {

        //now create a timer each ten seconds create for create 
        var mainTimer = new Timer
        {
            Interval = 100
        };
        mainTimer.Elapsed += (sender, eventArgs) =>
        {

            Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    SingleToneClass.Instance.DoWwork();

                    Thread.Sleep(10);
                }

            });
        };

        mainTimer.Start();
        Console.ReadLine();
    }
}

is it a good idea to use a timer in Singleton,any alternative


Solution

  • Your comment says a timer every ten seconds but you're actually getting one ten times a second.

    You then spawn new tasks on the thread pool that will run forever and will block with Thread.Sleep(). This will use all your thread pool threads and it will have to create new ones. BAD!

    If all you want is for the DoWork to be called periodically you should skip the timer and launch a single task.

            Task.Factory.StartNew(async () =>
            {
                while (true)
                {
                    SingleToneClass.Instance.DoWwork();
                    await Task.Delay(TimeSpan.FromSeconds(10));
                }
    
            });