I'm writing a windows service that fir开发者_StackOverflow社区ed up by a timer and does a time consuming for every minute. I want to limit the no. of service instances running at a time say 100. How I can do that? Any Idea?
EDITED: I want to limit the no. of threads started by the timer.
If you're using System.Threading.ThreadPool
, there's a function called SetMaxThreads that lets you control the maximum number of concurrently running threads. Also, make note of the remarks on that page about changing the number of concurrent threads.
That sounds like a very poor design -- and a memory/cpu hog. I'm not sure I understand what you mean when you say 100 windows services -- as a service is one service. At least in the sense of having a unique service. Are you firing up 100 applications running hidden in the background through a task manager? If so, you may be able to make that much nicer by creating a real windows service and having logic within that service to control the flow of the application (and the execution of multiple instances of your code running).
For instance, you could have a windows service with one main thread which would sleep for n. seconds and then execute. After the main thread wakes up, it would be responsible for spinning off new threads. As an example, you could use a thread pool whereas you could control the number of threads that were active. Your main thread would check the thread pool to determine if it's reached capacity, and if valid, spin off a new thread.
Main Service Thread
> Sleep n. seconds
> ThreadPool < 100?
> New Thread
This code demonstrates what you need.
Just use theSemaphoreSlim (Same as Semaphore, better performance) object to do it.
Think about the Semaphore as a counter. Each time you wait the counter goes one number down. In the end of the operation need to release it.
When the counter is 0, can't get Semaphore.
About the ThreadPool suggestions, I don't think it's a good idea because the thread pool is used in many parts of your application, not only this one.
class Program
{
private static SemaphoreSlim threadsSemaphore = new SemaphoreSlim(5, 5);
static void Main(string[] args)
{
Timer timer = new Timer(DoSomeWork, null, 0, 100);
Console.ReadKey();
}
private static void DoSomeWork(object state)
{
if (threadsSemaphore.Wait(TimeSpan.FromSeconds(1)))
{
try
{
Console.WriteLine("Doing work ...");
Thread.Sleep(1000);
}
finally
{
threadsSemaphore.Release();
}
}
else
{
Console.WriteLine("Skipping work", threadsSemaphore.CurrentCount);
}
}
}
精彩评论