C#:能否检测当前执行上下文是否在`lock(this)`内?
如果我想强制从锁内访问一个对象,如下所示:
var obj = new MyObject();
lock (obj)
{
obj.Date = DateTime.Now;
obj.Name = "My Name";
}
是否可以从 AddOne
和 RemoveOne
函数内检测是否当前执行上下文在锁内?
类似于:
Monitor.AreWeCurrentlyEnteredInto(this)
编辑:(为了澄清意图)
这里的意图是能够拒绝在锁之外进行的任何修改,以便对对象本身的所有更改都将是事务性和线程安全的。锁定对象本身内的互斥体并不能确保编辑的事务性质。
我知道可以这样做:
var obj = new MyObject();
obj.MonitorEnterThis();
try
{
obj.Date = DateTime.Now;
obj.Name = "My Name";
}
finally
{
obj.MonitorExitThis();
}
但这将允许任何其他线程调用添加/删除函数,而无需先调用Enter
,从而绕过保护。
编辑2:
这是我目前正在做的事情:
var obj = new MyObject();
using (var mylock = obj.Lock())
{
obj.SetDate(DateTime.Now, mylock);
obj.SetName("New Name", mylock);
}
这很简单,但有两个问题:
我正在实现 IDisposable mylock对象,有点 滥用 IDisposable 接口。
我想将
SetDate
和SetName
函数更改为 为清楚起见,属性。
If I have an object that I would like to force to be accessed from within a lock, like so:
var obj = new MyObject();
lock (obj)
{
obj.Date = DateTime.Now;
obj.Name = "My Name";
}
Is it possible, from within the AddOne
and RemoveOne
functions to detect whether the current execution context is within a lock?
Something like:
Monitor.AreWeCurrentlyEnteredInto(this)
Edit: (for clarification of intent)
The intent here is to be able to reject any modification made outside of the lock, so that all changes to the object itself will be transactional and thread-safe. Locking on a mutex within the object itself does not ensure a transactional nature to the edits.
I know that it is possible to do this:
var obj = new MyObject();
obj.MonitorEnterThis();
try
{
obj.Date = DateTime.Now;
obj.Name = "My Name";
}
finally
{
obj.MonitorExitThis();
}
But this would allow any other thread to call the Add/Remove functions without first calling the Enter
, thereby circumventing the protection.
Edit 2:
Here is what I'm currently doing:
var obj = new MyObject();
using (var mylock = obj.Lock())
{
obj.SetDate(DateTime.Now, mylock);
obj.SetName("New Name", mylock);
}
Which is simple enough, but it has two problems:
I'm implementing IDisposable on the
mylock object, which is a little bit
of an abuse of the IDisposable
interface.I would like to change the
SetDate
andSetName
functions to
Properties, for clarity.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
我认为如果不自己跟踪状态(例如通过使用某种信号量),这是不可能的。但即使是这样,这也会严重违反封装性。您的方法通常不应该关心它们是否在特定的锁定上下文中执行。
I don't think that's possible without tracking the state yourself (e.g. by using some kind of semaphore). But even if it were, that'd be a gross violation of encapsulation. Your methods usually shouldn't care whether or not they're executing in a particular locking context.
没有记录在案的方法来在运行时检查这种情况,如果有的话,我会对使用它的任何代码表示怀疑,因为任何基于调用堆栈改变其行为的代码都将很难调试。
真正的 ACID 语义实现起来并不简单,我个人也不会尝试;这就是我们数据库的用途,如果您需要代码快速/可移植,您可以使用内存数据库。如果您只想要强制单线程语义,那么这是一个更容易驯服的野兽,尽管作为免责声明,我应该提到,从长远来看,您最好简单地提供原子操作,而不是试图阻止多线程操作。线程访问。
假设您有充分的理由想要这样做。这是一个您可以使用的概念验证类:
这里发生了很多事情,但我会为您分解:
当前锁(每个线程)保存在
[ThreadStatic] 字段提供类型安全、线程本地存储。该字段在
ThreadGuard
的实例之间共享,但每个实例都使用自己的密钥 (Guid)。两个主要操作是
GetLock
,它验证没有锁被获取,然后添加自己的锁,以及ReleaseLock
,它验证锁是否存在< em>对于当前线程(因为记住,locks
是ThreadStatic
),如果满足条件则将其删除,否则抛出异常。最后一个操作
BeginGuardedOperation
旨在由拥有ThreadGuard
实例的类使用。它基本上是一种断言,它验证当前执行的线程是否拥有分配给此 ThreadGuard 的锁,如果不满足条件,则抛出异常。还有一个
ILock
接口(除了从IDisposable
派生之外,不执行任何操作),以及一个一次性内部ThreadGuardLock
来实现它,它保存对创建它的 ThreadGuard 的引用,并在释放时调用其 ReleaseLock 方法。请注意,ReleaseLock 是私有的,因此 ThreadGuardLock.Dispose 是对释放函数的唯一公共访问,这很好 - 我们只想要一个获取和释放的单点入口。要使用 ThreadGuard,您可以将其包含在另一个类中:
这一切都是使用 BeginGuardedOperation 方法作为断言,如前所述。请注意,我并不是试图保护读写冲突,而只是尝试保护多重写入冲突。如果您想要读写器同步,那么您需要需要相同的读取锁(可能不太好),在 MyGuardedClass 中使用额外的锁(最简单的解决方案)或更改 < code>ThreadGuard 使用
Monitor
类公开并获取真正的“锁”(小心)。这是一个可以使用的测试程序:
正如代码(希望)所暗示的那样,只有
TestWithLock
方法完全成功。 TestWithCrossThreading 方法部分成功 - 工作线程失败,但主线程没有问题(这也是这里所需的行为)。这并不是要成为生产就绪的代码,但它应该让您了解必须做什么才能(a)防止跨线程调用和(b)允许任何线程取得该线程的所有权。对象,只要没有其他东西使用它。
There's no documented method of checking for this kind of condition at runtime, and if there were, I'd be suspicious of any code that used it, because any code that alters its behaviour based on the call stack would be very difficult to debug.
True ACID semantics are not trivial to implement, and I personally wouldn't try; that's what we have databases for, and you can use an in-memory database if you need the code to be fast/portable. If you just want forced-single-threaded semantics, that is a somewhat easier beast to tame, although as a disclaimer I should mention that in the long run you'd be better off simply providing atomic operations as opposed to trying to prevent multi-threaded access.
Let's suppose that you have a very good reason for wanting to do this. Here is a proof-of-concept class you could use:
There's a lot going on here but I'll break it down for you:
Current locks (per thread) are held in a
[ThreadStatic]
field which provides type-safe, thread-local storage. The field is shared across instances of theThreadGuard
, but each instance uses its own key (Guid).The two main operations are
GetLock
, which verifies that no lock has already been taken and then adds its own lock, andReleaseLock
, which verifies that the lock exists for the current thread (because remember,locks
isThreadStatic
) and removes it if that condition is met, otherwise throws an exception.The last operation,
BeginGuardedOperation
, is intended to be used by classes that ownThreadGuard
instances. It's basically an assertion of sorts, it verifies that the currently-executed thread owns whichever lock is assigned to thisThreadGuard
, and throws if the condition isn't met.There's also an
ILock
interface (which doesn't do anything except derive fromIDisposable
), and a disposable innerThreadGuardLock
to implement it, which holds a reference to theThreadGuard
that created it and calls itsReleaseLock
method when disposed. Note thatReleaseLock
is private, so theThreadGuardLock.Dispose
is the only public access to the release function, which is good - we only want a single point of entry for acquisition and release.To use the
ThreadGuard
, you would include it in another class:All this does is use the
BeginGuardedOperation
method as an assertion, as described earlier. Note that I'm not attempting to protect read-write conflicts, only multiple-write conflicts. If you want reader-writer synchronization then you'd need to either require the same lock for reading (probably not so good), use an additional lock inMyGuardedClass
(the most straightforward solution) or alter theThreadGuard
to expose and acquire a true "lock" using theMonitor
class (be careful).And here's a test program to play with:
As the code (hopefully) implies, only the
TestWithLock
method completely succeeds. TheTestWithCrossThreading
method partially succeeds - the worker thread fails, but the main thread has no trouble (which, again, is the desired behaviour here).This isn't intended to be production-ready code, but it should give you the basic idea of what has to be done in order to both (a) prevent cross-thread calls and (b) allow any thread to take ownership of the object as long as nothing else is using it.
让我们重新设计您的类,使其真正像事务一样工作。
在调用 commit 之前,更改不会传播。
在提交中,您可以锁定目标对象并设置其属性。
Lets redisgn your class to make it actually work like transaction.
Changes will not be propagated until commit is called.
In commit you can take a lock and set the properties on the target object.
您可以重写
AddOne
和RemoveOne
来获取一个布尔标志,如果从锁调用该标志,则该标志设置为 true。我看不到任何其他方法。您还可以使用
ExecutionContext class
如果你想了解有关当前执行上下文的信息。您可以通过调用ExecutionContext.Capture()
。You can override
AddOne
andRemoveOne
to take a boolean flag that is set to true if it's being called from a lock. I don't see any other way.You can also play with the
ExecutionContext class
if you want to know something about the current execution context. You can get the current context by callingExecutionContext.Capture()
.使用线程本地存储,您可以存储锁的进入和退出。
using thread local storage you can store the entering and exiting of a lock.
如果您的要求是必须在方法 AddOne() 或 RemoveOne() 的持续时间内获取锁,那么为什么不简单地在每个方法内获取锁呢?如果调用者已经为您获取了锁,那么这应该不是问题。
但是,如果您的要求是必须在一起调用 AddOne() 和 RemoveOne() 之前获取锁(因为在实例上执行的其他并发操作可能不安全),那么也许您应该考虑更改公共接口,以便可以锁定内部处理,无需考虑客户端代码的细节。
完成后者的一种可能方法是提供必须在 AddOne 和 RemoveOne 之前和之后调用的 Begin-Changes 和 End-Changes 方法。如果在 Begin-End 范围之外调用 AddOne 或 RemoveOne,则应引发异常。
If your requirement is that the lock must be acquired for the duration of either method AddOne() or RemoveOne(), then why not simply acquire the lock inside each method? It shouldn't be a problem if the caller has already acquired the lock for you.
However, if your requirement is that the lock must be acquired before calling AddOne() and RemoveOne() together (because other concurrent operations performed on the instance are potentially unsafe), then maybe you should consider changing the public interface so that locking can be handled internally without concerning client code with the details.
One possible way to accomplish the later would be to provide methods for Begin- and End-Changes that have to be called before and after AddOne and RemoveOne. An exception should be raised if AddOne or RemoveOne is called outside of the Begin-End scope.
我遇到了同样的问题并创建了一个如下所示的帮助程序类:
然后您可以创建一个像这样包装的实例:
并像这样使用它:
对于我的特殊情况,我只想要一个强制锁(两个线程不应该如果他们行为良好的话,尝试同时获取锁),所以我抛出一个异常。您可以轻松修改它以执行更典型的锁定,并且仍然利用 IsBusy。
I ran into this same problem and created a helper class that looks like this:
You can then create an instance wrapped like this:
And use it like this:
For my particular case, I only wanted an enforcing lock (two threads shouldn't ever try to acquire the lock at the same time if they're well-behaved), so I throw an exception. You can easily modify it to perform more typical locking and still take advantage of the IsBusy.