C # WinService with timer-controlled threading

I have a Windows service class (inherited from ServiceBase), which at the time of construction is provided with a list of objects. Each operation describes a virtual DoWork () method.
The point of the Service class is to manage all basic operations, add / remove them to the list at runtime, and execute their DoWork () method in the ThreadPool thread.
Each operation has a System.Timers.Timer object that is created and launched with the Operation class. Each operation throws an event to signal to the control class that its own timer has been raised, and it must run its own DoWork () method in the stream.

The TimedService class associates each past timer event with a method that requests a thread from the pool:

private void CheckOperationsList(object source, EventArgs e)
{
 try
  {
    foreach (Operation op in this._operationsList)
    {
      lock (this._operationsList)
      {
        op.TimerElapsed += new Operation.ElapsedEventHandler(this.RequestThreadFromPool);
      }
    }
  }
  catch (Exception ex) { this._ManEV.WriteError(this._serviceName, ex.Message); }
}  

And, of course, the RequestThreadFromPool (object sender, EventArgs e) method does the following:

    ThreadPool.QueueUserWorkItem(new WaitCallback(((Operation)sender).DoWork), new object());  

I get weird behavior from processes. I tried to implement a fictitious operation with a timer set to 10 seconds, which simply holds the processor for several seconds:

for (Int16 i = 0; i < Int16.MaxValue; i++)
  {
    for (short j = 0; j < short.MaxValue; j++)
    { }
  }  

Each time the operation is performed separately in the queue (I pass a list of only one element to the Service), everything is fine. The process spawns its own thread, holds the processor for a couple of seconds, and then leaves.

I implemented a lighter version of the dummy method above (basically the same without an inner loop) to simulate a light flow.

( !), , .
. Visual Studio , - , , ; Operation .!

catch {} es DoWork() try {}, .

, , (.. ), . , , .

, System.Timers.Timer - Stop() Event, . 4-5 DoWork(), .

edit : . I.e:

public class TestLongOperation : Operation
{
  public TestLongOperation(double secondsInterval) : base(secondsInterval) { }
  public override void Work(object buh)
  {
    for (Int16 i = 0; i < Int16.MaxValue; i++)
    {
      for (short j = 0; j < short.MaxValue; j++)
      { }
  }
}

}

? , . .

+3
2

, , , , , , .

. Thread.sleep. , . , .

:

( )

bool running = true;

while (running)
{

  //do processing


  /sleep for 'timer' interval
  Thread.Sleep(interval)
}

?

+1

:

, , "".

? , . , ?

, ? . , ? , , .

Timer.SynchronizingObject Property, , Timer ThreadPool.

0

Source: https://habr.com/ru/post/1786674/


All Articles