给定一个可以并行运行的动作列表,我想考虑一个或另一个动作不希望与其他动作并行执行(由动作的属性确定)。
考虑这种简化:
private static Random random;
static void Main (string[] args)
{
random = new Random();
new Thread (() => DoSomething (false)).Start();
new Thread (() => DoSomething (false)).Start();
new Thread (() => DoSomething (true)).Start();
new Thread (() => DoSomething (false)).Start();
new Thread (() => DoSomething (false)).Start();
Console.Read();
}
private static void DoSomething(bool singlethread)
{
Console.WriteLine ("Entering " + Thread.CurrentThread.ManagedThreadId);
if (singlethread)
Console.WriteLine ("Im the only one!!!");
Thread.Sleep (random.Next (1000, 5000));
Console.WriteLine ("Exiting " + Thread.CurrentThread.ManagedThreadId);
}
如何同步操作,以便操作 3 等待操作 1 和 2 退出,然后阻止操作 4 和 5?
更新
这是我在 Rob 的帮助下想出的:
public class Lock : IDisposable
{
private static readonly object _object = new object();
private static readonly AutoResetEvent _event = new AutoResetEvent (false);
private static int _count;
public static IDisposable Get (bool exclusive)
{
return new Lock (exclusive);
}
private readonly bool _wasTaken;
private Lock (bool exclusive)
{
if (exclusive)
{
Monitor.Enter (_object, ref _wasTaken);
_count++;
while (_count > 1)
_event.WaitOne();
}
else
{
lock (_object)
Interlocked.Increment (ref _count);
}
}
public void Dispose ()
{
Interlocked.Decrement (ref _count);
if (_wasTaken)
Monitor.Exit (_object);
_event.Set();
}
}
像这样使用:
using (Lock.Get(exclusive: false/true)
{
DoSomething();
}