c# - Try-Finally 与 Thread.BeginCriticalRegion

标签 c# .net multithreading

据我了解,必须在线程中止生效之前完成 finally block 。出于什么目的应该使用 Thread.BeginCriticalRegion,冒着终止 appdomain 的风险?

例子:

try
{
}
finally
{
    CriticalOperation();
}

Thread.BeginCriticalRegion();
CriticalOperation();
Thread.EndCriticalRegion();

最佳答案

为了让它变得非常简单,try...finally... 防止 Thread.Abort(finally 部分完全protected 且不能被中断/将始终被执行),而 Thread.BeginCriticalRegion() 仅向 .NET 的运行时提供一些元信息:

来自 https://learn.microsoft.com/nl-nl/archive/blogs/bclteam/constrained-execution-regions-and-other-errata-brian-grunkemeyer

Critical regions don't really do much.

...

The first effect for critical regions is a way of informing the CLR that a lock is being held by a block of managed code

(注意,这只是信息……运行时做什么是它的问题。这里不能保证)

The second effect is that memory allocations within that block of code are marked as appdomain-critical.

然后它解释了运行时应该优先考虑为该代码块分配内存...所以运行时的其他元信息没有程序员的保证

关于c# - Try-Finally 与 Thread.BeginCriticalRegion,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28786569/

相关文章:

c# - 如何在 C# 中获取可移动磁盘列表?

Python:线程回调不适用于守护进程模式?

c# - 我如何告诉我的 .NET 程序集 COM 对象的详细信息存储在注册表中的哪个位置?

c# - 从另一个类 c# 更新 gui

c# - 设置动态创建的 asp :button 的 OnClick 属性

c# - 在 C# 中键入时查找

c# - ASP .NET - 设置 DetailsView TextBox 的值

.NET 远程/在家工作契约(Contract)资源...报酬丰厚

linux - 性能 - 多线程或多进程应用程序

java - 代码性能比较,线程与非线程