【问题标题】:Nested thread breaks timer [duplicate]嵌套线程中断计时器[重复]
【发布时间】:2021-11-11 06:08:02
【问题描述】:

我有一个 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();                                                
    }

【问题讨论】:

  • 如果您在启动后立即加入线程,那么您不需要线程。
  • 为什么要取消计时器并从计时器的滴答处理程序中启动另一个计时器?
  • 由于很多原因,您拥有的少量代码显然是错误的,我认为如果您解释一下您要实现的目标,这可能会更容易。
  • 这是原始代码的简化版本。 SomeThreadMethod 内部启动了多个线程
  • 那么有两个问题:定时器没有按预期使用,这里你可能使用了太多线程。因此,如果您可以发布 minimal reproducible example 并说明您的目标是什么,那就太好了。

标签: c# multithreading timer


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2011-09-04
    • 2019-02-16
    • 1970-01-01
    • 2013-02-16
    • 2020-01-02
    • 1970-01-01
    • 1970-01-01
    • 2017-10-06
    • 1970-01-01
    相关资源
    最近更新 更多