开发者

While(true) loop get stuck in Windows Service without any log or eventLog

开发者 https://www.devze.com 2023-03-13 06:32 出处:网络
I have a windows Service with a main method that includes 5 tasks: 4 System.Timers.Timer() 1 method with infinit loop While(true) handled by a separat thread

I have a windows Service with a main method that includes 5 tasks:

  • 4 System.Timers.Timer()
  • 1 method with infinit loop While(true) handled by a separat thread

N.B: before each method execution a description like "Send command starting now ..." is written in .log file

Yesterday when I checked the log, I noted that all 4 timers methods logs into log file and execute the code, but the method with the infinite loop While(true) logged nothing.

Could you provide me your suggestion about what can cause the infinite loop?

 private void StartThread(){
        if (_Thread != null){
            if (_Thread.IsAlive){
                return;
            }
        }

         Log.Write("thread started.");
        _Thread = new Thread(SchedulerWorker);
        _Thread.IsBackground = true;
        _Thread.Name = "scheduler th开发者_开发技巧read";
        _Thread.Priority = ThreadPriority.Lowest;
        _Thread.Start();
    }

    private void SchedulerWorker(){
        while (true){
            try{
                DoScheduleWork();
            }
            catch (Exception ex){
                Log.Write("Worker exception : " +  ex);
            }
            Thread.Sleep(TIMER_INTERVAL);
        }
    }


First, you need to check Log object for multithread support. If it works in main thread does not mean that it works in another thread well at same time. When work with multiple threads you always need to keep in mind about concurrency and other important rules. At least, may be you should place Log into lock statement (I don't know internal structure of your Log object).

Second, don't think that Log not throws exceptions or exceptions don't exists inside catch block. Is quite possible that thread crashes here:

    catch (Exception ex)
    {
        Log.Write("Worker exception : " +  ex);
    }

Third, try simpliest and safest logging first for your debug purposes. Usually Windows Services logs their events into system journal. But it not well suited for debugging, it is rather a part of Service "interface". Try to use Trace class from System.Diagnostics.

using System.Diagnostics;
...
   catch (Exception ex)
   {
       Trace.WriteLine("Worker exception : " +  ex);
   }

For multithreaded applications you need more accurately write, verify and debug every step of your code before think that it works as expected. Multithreading in most cases significantly increases the complexity of development.

Creation of Service applications is also not a trivial task. For example using of forms in Services is strongly discouraged and complicates debugging.

0

精彩评论

暂无评论...
验证码 换一张
取 消