.net MethodImplOptions.Synchronized 有什么作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2223656/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 13:52:43  来源:igfitidea点击:

What does MethodImplOptions.Synchronized do?

.netmultithreading

提问by Amitabh

What does MethodImplOptions.Synchronizeddo?

有什么作用MethodImplOptions.Synchronized

Is the code below

是下面的代码

[MethodImpl(MethodImplOptions.Synchronized)]
public void Method()
{
    MethodImpl();
}

equivalent to

相当于

public void Method()
{
    lock(this)
    {
        MethodImpl();
    }
}

采纳答案by David Basarab

This was answered by Mr. Jon Skeeton another site.

这是由Jon Skeet 先生在另一个网站上回答的。

Quote from Post

来自邮政的报价

It's the equivalent to putting lock(this) round the whole method call.

这相当于将 lock(this) 放在整个方法调用中。

The post has more example code.

该帖子有更多示例代码。

回答by Rico Suter

For static methods it's the same as:

对于静态方法,它与以下相同:

public class MyClass
{
    public static void Method()
    {
        lock(typeof(MyClass))
        {
           MethodImpl();
        }
    }
}

http://social.msdn.microsoft.com/Forums/en-US/b6a72e00-d4cc-4f29-a6a0-b27551f78b9b/methodimploptionssynchronized-vs-lock

http://social.msdn.microsoft.com/Forums/en-US/b6a72e00-d4cc-4f29-a6a0-b27551f78b9b/methodimploptionssynchronized-vs-lock

回答by Michael Stoll