gpt4 book ai didi

.net - 退出上下文对于 WaitHandle.WaitOne 意味着什么?

转载 作者:行者123 更新时间:2023-12-04 00:45:07 25 4
gpt4 key购买 nike

我正在尝试使用互斥锁来保护多个线程对某些硬件的访问,但我对 exitContext 的内容感到困惑参数意味着/做:

public virtual bool WaitOne (
int millisecondsTimeout,
bool exitContext
)

The docs说:

exitContext - true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it afterward; otherwise, false.



...但这实际上意味着什么,将其设置为 true 或 false 的后果是什么?我现在已经将它设置为 true 并且代码似乎可以工作,但我很紧张,因为我不完全理解它到底在做什么!

最佳答案

它还解释了 further down the page under Remarks那:

Notes on Exiting the Context

The exitContext parameter has no effect unless the WaitOne method is called from inside a nondefault managed context. This can happen if your thread is inside a call to an instance of a class derived from ContextBoundObject. Even if you are currently executing a method on a class that does not derive from ContextBoundObject, like String, you can be in a nondefault context if a ContextBoundObject is on your stack in the current application domain.

When your code is executing in a nondefault context, specifying true for exitContext causes the thread to exit the nondefault managed context (that is, to transition to the default context) before executing the WaitOne method. The thread returns to the original nondefault context after the call to the WaitOne method completes.

This can be useful when the context-bound class has SynchronizationAttribute. In that case, all calls to members of the class are automatically synchronized, and the synchronization domain is the entire body of code for the class. If code in the call stack of a member calls the WaitOne method and specifies true for exitContext, the thread exits the synchronization domain, allowing a thread that is blocked on a call to any member of the object to proceed. When the WaitOne method returns, the thread that made the call must wait to reenter the synchronization domain.

关于.net - 退出上下文对于 WaitHandle.WaitOne 意味着什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7824497/

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