gpt4 book ai didi

c# - 静态构造函数是否作为 CER 运行?

转载 作者:行者123 更新时间:2023-11-30 17:25:31 28 4
gpt4 key购买 nike

我正在测试以下代码:

private static void Main()
{
var t = new Thread(() =>
{
var m = new MyCls();
m.DoWork();
});
t.Start();

// simulate time-consuming job
Thread.Sleep(1000);

t.Abort();
Console.Write("\nDone");
}


public class MyCls
{
static MyCls()
{
for (int i = 0; i < 10; i++)
{
Console.Write(i);
Thread.Sleep(1000);
}
}

public void DoWork()
{
Console.WriteLine("executing DoWork..");
}
}

我得到的输出是:

0123456789
Done

似乎 t.Abort() 调用阻塞了主线程,直到静态构造函数的执行完成,并且根据 documentation :

The thread that calls Abort might block if the thread that is being aborted is in a protected region of code, such as a catch block, finally block, or constrained execution region.

我的问题是:

  1. 静态构造函数真的作为受限执行区 (CER) 运行吗?
  2. 如果是,还有哪些其他代码块作为 CER 运行?

最佳答案

似乎静态构造函数保证已经完成,几乎。

可以使用 RuntimeHelpers.RunClassConstructor 显式调用静态构造函数其中“确保指定类型的类型初始值设定项(也称为静态构造函数)已运行”

在您的示例中,代码可以编写如下。

var t = new Thread(() =>
{
System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(MyCls).TypeHandle);
var m = new MyCls();
});

RunClassConstructor 调用 _RunClassConstructor用以下评论注释。

In the absence of class constructor deadlock conditions, the call is further guaranteed to have completed.

// RunClassConstructor causes the class constructor for the given type to be triggered
// in the current domain. After this call returns, the class constructor is guaranteed to
// have at least been started by some thread. In the absence of class constructor
// deadlock conditions, the call is further guaranteed to have completed.
//
// This call will generate an exception if the specified class constructor threw an
// exception when it ran.
[System.Security.SecuritySafeCritical]
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void _RunClassConstructor(RuntimeType type);

关于c# - 静态构造函数是否作为 CER 运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58458842/

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