gpt4 book ai didi

c# - 用于 WaitHandle.WaitOne 方法的 exitContext 是什么

转载 作者:IT王子 更新时间:2023-10-29 04:06:39 24 4
gpt4 key购买 nike

例子

System.Threading.AutoResetEvent e = new System.Threading.AutoResetEvent(false);
bool b = e.WaitOne(1000, false);

我做过很多多线程开发,一直想知道那个方法有什么用。 WaitOne 上的第二个 bool 参数称为 exitContext。 MS 帮助说明 “如果在等待之前退出上下文的同步域(如果在同步上下文中),并在之后重新获取它,则为 true;否则为 false。”

有人知道这是什么意思吗?这是我应该担心的事情吗?

亲切的问候诺尔

最佳答案

我不能要求信用(因此 wiki),但有一个很好的答案 here .

从链接中回答问题,作者 Sasha Goldshtein

The CLR has support for a notion called contexts. A context is alogical grouping of objects. When a method call is made on an objectthat is inside your context, nothing in particular happens except forthe method itself. When a method call is made on an object that isoutside your context, then "something" might happen before the methoditself is executed. All .NET classes derived from ContextBoundObjectwill be associated with a context at runtime.

An example of that "something" that can happen before the method iscalled would be enforcing synchronization. An object that derivesfrom ContextBoundObject and specifies the [Synchronization] attributewill get automatic synchronization services from the runtime. Thismeans that only one thread will ever be able to execute within theobject's context.

The exitContext parameter of the WaitOne method specifies whether toleave the synchronization context before issuing the wait. Thisenables reentrancy. Here's a scenario where this is necessary:

Code Snippet [Synchronization] public class MyCounter :ContextBoundObject {

private int _expectedCounterVal; private int _currentCounterVal;private ManualResetEvent _event = new ManualResetEvent(false);

public void WaitUntilCounterIs(int counterVal) {
_expectedCounterVal = counterVal; _event.WaitOne(TimeSpan.FromDays(1), true); }

public void IncrementCounter() { if (++_currentCounterVal >=_expectedCounterVal) { _event.Set(); } } }

In this case, if the WaitUntilCounterIs method is issued without theexitContext=true parameter of the WaitOne method, then no other threadwill be able to ever call the IncrementCounter method on the object,resulting in a deadlock. However, once exitContext=true is specified,other threads can enter the IncrementCounter method and signal theevent at some point, even though the WaitUntilCounterIs method has notyet returned.

关于c# - 用于 WaitHandle.WaitOne 方法的 exitContext 是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/755608/

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