Home > Net >  Nested thread breaks timer [duplicate]
Nested thread breaks timer [duplicate]

Time:09-16

I have a TimerMethod(), that calls itself at five-second intervals. So far all is good, the timer loops as expected. Inside the timer, I put a method - SomeThreadMethod(). If I do not start a thread inside that SomeThreadMethod, all is good, the timer continues looping. However, if I start a thread, the timer stops looping. What is wrong with that code and how can I use a thread inside a looping timer?

    public void TimerMethod()
    {
        Timer timer = new Timer((obj) =>
        {
            // this point in the code is always reached
            System.Diagnostics.Debug.WriteLine("before function call");

            SomeThreadMethod();
             
            // this point is never reached, if there is a nested Thread
            // inside SomeThreadMethod()
            System.Diagnostics.Debug.WriteLine("after function call");


            TimerMethod();
            timer.Dispose();
        },
        null, 5000, Timeout.Infinite);
    }


    public void SomeThreadMethod()
    {
        // if I use thread here, then the hosting 
        // TimerMethod stops looping. Why???
        // If I do not use a thread here, then
        // the timer loops normally
        Thread someThread = new Thread(() =>
            {
                // do something inside thread
            });

        someThread .Start();
        someThread .Join();                                                
    }

CodePudding user response:

I don't know what your plan is. Here is a working Version of your thread starting Timer. Here the Thread does not break the Timer.

using System;
using System.Threading;
using System.Timers;

namespace TestTimerThread
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Press key to end");
            System.Timers.Timer timer = new System.Timers.Timer()
            {
                Interval = 5000
            };
            timer.Elapsed  = OnTimerElapsed;
            timer.Start();

            Console.ReadKey();
            timer.Stop();
        }

        private static void OnTimerElapsed(object sender, ElapsedEventArgs e)
        {
            Console.WriteLine("Elapsed before function call");
            RunThread();
            Console.WriteLine("Elapsed after function call");
        }

        private static void RunThread()
        {
            Thread thread = new Thread(() =>
            {
                Console.WriteLine("in Thread");
            });
            thread.Start();
        }
    }
}
  • Related