【发布时间】:2015-10-15 03:56:04
【问题描述】:
我创建了一个调度程序,它以 x 分钟的时间间隔执行一段程序。如果程序执行需要更多时间,则下一个作业不应等待当前作业完成。我正在使用System.Timers.Timer。
_scheduler = new System.Timers.Timer(SomeMinutes);
_scheduler.Elapsed += new ElapsedEventHandler(OnTimedEvent);
_scheduler.Enabled = true;
_scheduler.AutoReset = true;
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
lock(obj)
{
//Critical Section
}
}
如果我使用锁,下一个线程等待当前线程释放锁。我不想要这种行为。如果一个线程在临界区获得了锁对象,那么另一个线程应该退出而不执行临界区
【问题讨论】:
-
我会认为指定一个超时时间,例如
cs.Lock(timeout)就可以了? -
我没有得到 cs.Lock(timeout)。什么是cs对象?
-
抱歉,实际上您需要使用Monitor,因为.NET 不像
Mutex那样包装操作系统关键部分。特别是Monitor.TryEnter
标签: c# multithreading