【发布时间】:2013-09-28 00:46:51
【问题描述】:
我正在阅读 Constrained Execution Regions and other errata [Brian Grunkemeyer] 以试图了解受约束的执行区域,但是我在理解以下示例时遇到了一些问题:
RuntimeHelpers.PrepareConstrainedRegions();
try {
// Prepare my backout code
MethodInfo m = _list.GetType().GetMethod("RemoveAt", new Type[] { typeof(int) });
RuntimeHelpers.PrepareMethod(m.MethodHandle);
IEnumerator en = c.GetEnumerator();
while(en.MoveNext()) {
_list.Insert(index++, en.Current);
// Assuming that these lines aren't reordered.
numAdded++;
}
_version++;
}
catch(Exception) {
// Reliable backout code
while(numAdded > 0) {
_list.RemoveAt(index--);
numAdded--;
}
throw;
}
我的理解是,try 块是不受约束的,只有 finally 和 catch 块受到约束。这意味着在try 块期间可以随时抛出异步异常(例如ThreadAbortException),特别是它可以在numAdded++ 之前但在_list.Insert 之后抛出。在这种情况下,退出代码会从 _list 中删除一项太少的项目。
鉴于此,我很难理解本示例中受约束的执行区域的用途。
我对此的理解是正确的还是我遗漏了什么?
【问题讨论】:
-
这里肯定有问题。