你需要Semaphores与限制1和超时时间0毫秒
通过使用旗语你可以说,只有线程的数量有限,在同一时间访问一段代码。
如何使用它
见this sample您需要使用此方法等待
bool WaitOne(int millisecondsTimeout)
指定超时时间= 0;这样你的等待线程将等待0秒这意味着他们会简单地跳过代码
Example
class SemaphoreExample
{
// Three reserved slots for threads
public static Semaphore Pool = new Semaphore(1, 0);
public static void Main(string[] args)
{
// Create and start 20 threads
for (int i = 0; i < 20; i++)
{
Thread t = new Thread(new ThreadStart(DoWork));
t.Start();
}
Console.ReadLine();
}
private static void DoWork()
{
// Wait 0 miliseconds
SemaphoreExample.Pool.WaitOne(0);
#region Area Protected By Semaphore
Console.WriteLine("Acquired slot...");
for (int i = 0; i < 10; i++)
{
Console.WriteLine(i + 1);
}
Console.WriteLine("Released slot...");
#endregion
// Release the semaphore slot
SemaphoreExample.Pool.Release();
}
}
为什么你认为我想使用接近零的超时?为什么不只是零? – 2011-12-28 05:46:37
@Louis:你可以使用0的时间间隔(或者等价地,使用另一个不需要TimeSpan的超载)。在放弃之前至少等待一小段时间的资源是很常见的。你不必,如果你不想。 :) – Ani 2011-12-28 05:48:37