How do i run max n threads开发者_运维百科 in a c# code block?
I'll like something easy and short like this pseudocode
lock (this, 5)
{
//do some work
}
EDIT: This is not a shared memory, race condition thing. The problem is that I have alot of threads. But I found out the a resource used in one part of the code is failing when used too much in parallel. I could use a objecpool, but I hoped i could do it even more easy.
Use a Semaphore
Limits the number of threads that can access a resource or pool of resources concurrently.
You cannot use the lock as such, because this marks a critical section for single execution only. You will need to use your own semaphores, I think, along these lines ( not code - just concept )
var semaphore
semaphore.flag 5 times
semaphore.wait
do code
semaphore.flag
I would say that if you are going to use this, you need to understand what you are doing and how it works. However, it is the mechanism that lock uses, so you should achieve what is needed.
I also think a semaphore is what you're looking for. In .NET 4.0, however, there might be another way for you as well. If you like 5 threads to run the same code concurrently, you could put it into a Task
and use a TaskScheduler
to make .NET spawn at most 5 threads. Just set the MaximumConcurrencyLevel
property.
This does not do any semaphore-like thinks, so other threads might enter into the section too! See also Task Parallel Library (MSDN) for more information.
you could use a ThreadPool instead which allow you to set up the min/max number of thread
have a llok at the below:
http://msdn.microsoft.com/en-us/library/system.threading.threadpool.setmaxthreads.aspx
you should avoid to lock (this) because you risk to have dead-locking. The looking should be as much granula as possible.
精彩评论