MethodImp属性的用法
1.MethodImpAttribute说明
指定如何实现方法的详细信息, 此类不能被继承。来自msdn
应用场景
通常Monitor用于同步对类的静态方法或实例方法的访问时,如果临界区跨越整个方法,则可以通过System.Runtime.CompilerServices.MethodImplAttribute将置于方法上,并在的构造函数中Synchronized指定System.Runtime.CompilerServices.MethodImplAttribute值来实现锁定工具。 使用此属性时, 不需要使用Monitor.Enter和Monitor.Exit方法。-
class Program
{
private static int _number = 0;
static void Main(string[] args)
{
try
{
TestMonitorAttribute();
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Console.ReadLine();
}
static void TestMonitorAttribute()
{
for (int i = 1; i < 4; i++)
{
Thread t = new Thread(NumberAdd);
t.Name = "Thread_" + i;
t.Start();
}
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
static void NumberAdd()
{
_number++;
Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId}:{_number.ToString()}");
}
}

[1]: https://docs.microsoft.com/zh-cn/dotnet/api/system.runtime.compilerservices.methodimplattribute?redirectedfrom=MSDN&view=netframework-4.8
3728

被折叠的 条评论
为什么被折叠?



