嵌套线程中断计时器

Nested thread breaks timer

我有一个 TimerMethod(),它每隔五秒调用一次。到目前为止一切都很好,计时器按预期循环。在计时器内部,我放置了一个方法 - SomeThreadMethod()。如果我不在那个 SomeThreadMethod 中启动一个线程,一切都很好,计时器继续循环。但是,如果我启动一个线程,计时器将停止循环。该代码有什么问题?我如何在循环计时器中使用线程?

    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();                                                
    }

我不知道你的计划是什么。这是您的线程启动计时器的工作版本。这里线程不会破坏定时器。

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();
        }
    }
}