System.Timer passed in a separate thread and supported thread restriction

I want to limit the number of threads in my multi-threaded WCF service. So, I am using the ThreadPool.SetMaxThread function. Now I want to use System.Timers to generate events at given intervals.

But my service at the same time gets a lot of actions to perform in the thread pool. When my timer has expired, the action is queued in ThreadPool (I sometimes have 100,000 tasks waiting) and therefore slower to complete.

Is there a way to execute my past event earlier? For example, setting a priority job in a queue on threadpool? Or an expired event outside the stream?

I want to keep my global thread limit in my service.

+4
source share
3 answers

If you need to limit the number of threads only to protect denial of service attacks, the best option here is to limit the maxConcurrentCalls property for ServiceThrottlingBehavior . see details http://msdn.microsoft.com/en-us/library/system.servicemodel.description.servicethrottlingbehavior.maxconcurrentcalls.aspx

By default, this setting is 16 times the number of processors.

If so, you can avoid limiting the maximum number of threads for a thread pool.

Then your WCF service will be protected from multiple simultaneous calls, and at the same time, timer events will be processed without delay.

+1
source

You can, if an option, convert your code to support a producer-consumer pattern using Taskfactory in combination with a blocking collection.

The collection allows you to set a maximum limit.

From the link below:

 - An implementation of the Producer-Consumer pattern. - Concurrent adding and taking of items from multiple threads. 

- additional maximum capacity.

 - Insertion and removal operations that block when collection is empty or full. - Insertion and removal "try" operations that do not block or that block up to a specified period of time. - Encapsulates any collection type that implements IProducerConsumerCollection(Of T) - Cancellation with cancellation tokens. - Two kinds of enumeration with foreach (For Each in Visual Basic): - Read-only enumeration. - Enumeration that removes items as they are enumerated. 

Here are some resources worth checking out:

blocking-collection-and-the-producer-consumer-problem
http://msdn.microsoft.com/en-us/library/dd997371.aspx
http://msdn.microsoft.com/en-us/library/dd267312.aspx

+1
source

This .NET Matters MSDN article ThreadPoolPriority and MethodImplAttribute is a bit outdated, but I think this approach is still valid. Its solution is to create a ThreadPriorityPool that determines that the next available thread from the managed pool should execute.

Another option is to try the Intelligent Thread Pool in CodeProject. It explicitly supports prioritizing work items.

0
source

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


All Articles