gpt4 book ai didi

c# - 如果另一个线程已获得关键部分的锁,如何停止线程?

转载 作者:行者123 更新时间:2023-11-30 16:05:46 25 4
gpt4 key购买 nike

我创建了一个调度程序,它以 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
}
}

如果我使用锁,下一个线程等待当前线程释放锁。我不想要这种行为。如果一个线程在临界区获得锁对象,那么另一个线程应该退出而不执行临界区

最佳答案

您可以使用Monitor

MSDN:

The Monitor class controls access to objects by granting a lock for an object to a single thread. Object locks provide the ability to restrict access to a block of code, commonly called a critical section. While a thread owns the lock for an object, no other thread can acquire that lock. You can also use Monitor class to ensure that no other thread is allowed to access a section of application code being executed by the lock owner, unless the other thread is executing the code using a different locked object. More please...

但您可能会问,“这不是 c# 的 lock() 所做的吗?” 在某些方面是的。然而,Monitor 的真正好处是,您可以尝试获取锁并指定超时 等待,而不是阻塞线程直到时间可能结束或至少直到你读完那本 war 与和平

此外,与 Mutex 不同,Monitor 使用起来很轻量级!就像 Windows 操作系统深层管道中的关键部分一样。

更改您的代码

private void OnTimedEvent(object source, ElapsedEventArgs e)
{
lock(obj)
{
//Critical Section
}
}

...到:

object _locker = new object();
const int SomeTimeout=1000;

private void OnTimedEvent(object source, ElapsedEventArgs e)
{
if (!Monitor.TryEnter(_locker, SomeTimeout))
{
throw new TimeoutException("Oh darn");
}

try
{
// we have the lock so do something
}
finally
{
// must ensure to release the lock safely
Monitor.Exit(_locker);
}
}

以下是 MSDN 对 TryEnter 的说明:

Attempts, for the specified number of milliseconds, to acquire an exclusive lock on the specified object - Tell me more...

关于c# - 如果另一个线程已获得关键部分的锁,如何停止线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33139623/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com