Reputation: 65
I want to limit my number of threads in my multi-threaded WCF service. So, I use ThreadPool.SetMaxThread
function. Now, I want to use System.Timers
to generate events at given intervals.
But, my service receives at the meantime many actions to execute in the thread pool. When my timer is elapsed, the action is queued in the ThreadPool (I've sometimes 100,000 tasks in expectations) and therefore slow to execute.
Is there a way to execute my elapsed event before? For example, by setting priority task queued on the threadpool? Or Elapsed the event outside of the threadpool?
I want to keep my global limit of thread in my service.
Upvotes: 4
Views: 455
Reputation: 5801
This .NET Matters MSDN article ThreadPoolPriority, and MethodImplAttribute is a bit old but I think the approach is still valid. His solution is to create a ThreadPriorityPool that defines what the next available thread from the managed pool should execute.
Another option is to try the Smart Thread Pool on CodeProject. It explicitly supports ordering work items by priority.
Upvotes: 0
Reputation:
You could, if an option, convert your code to support a producer-consumer pattern by using the Taskfactory
combined with a blocking collection.
The collection allow you to set a max limit.
From the link below:
- An implementation of the Producer-Consumer pattern. - Concurrent adding and taking of items from multiple threads.
> - Optional 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 to check 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
Upvotes: 1
Reputation: 6418
If you need to limit threads number only to protect denial of service attacks then better option here is to limit maxConcurrentCalls
property for ServiceThrottlingBehavior
.
see details at http://msdn.microsoft.com/en-us/library/system.servicemodel.description.servicethrottlingbehavior.maxconcurrentcalls.aspx
By default this parameter is 16 times the processor count.
If so then you can avoid to limit max threads number for thread pool.
Then your WCF service will be safe from multiple concurrent calls point of view and at the same time timer events will be processed witn no delay.
Upvotes: 1