哪种方法最适合线程同步? [英] Which way is the best for thread synchronization?

查看:77
本文介绍了哪种方法最适合线程同步?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

哪个最健壮? 和有什么区别?

Which is the most robust? And what is difference?

1.

[Synchronization]
public class Person : ContextBoundObject
{
    public void Print(){
        Console.WriteLine ("Start");
        Thread.Sleep (100);
        Console.WriteLine ("END");
    }
}

2.

        private readonly object obj = new object();
        public void Print(){
            lock (obj) {
                Console.WriteLine ("Start");
                Thread.Sleep (100);
                Console.WriteLine ("END");
            }
        }

顺便说一句,主要:

            Person a = new Person ();
            for (int i = 0; i < 10; i++) {
                new Thread (a.Print).Start ();
            }

我们可以使用两种方式互换吗?

Can we use this two way interchangeable ?

推荐答案

SynchronizationAttributeContextBoundObject是.NET Remoting概念.它们不适合在通用代码中使用,只能在完整的.NET框架上运行(不适用于Windows Phone,Windows Store应用程序或Silverlight).另外,它迫使您使您的类继承ContextBoundObject,这可能是不希望的.

SynchronizationAttribute and ContextBoundObject are .NET Remoting concepts; they're not intended for use in general-purpose code, and will only work on the full .NET framework (not in Windows Phone, Windows Store apps or Silverlight). Also, it forces you to make your class inherit ContextBoundObject, which might not be desirable.

另一方面,lock可以在任何地方使用,并且不会强迫您继承特定的类;它也更细粒度,因为您可以将其仅应用于需要它的代码,而不是整个类.

On the other hand, lock will work anywhere, and doesn't force you to inherit a specific class; it is also more fine-grained, as you can apply it to just the code that needs it, rather than the entire class.

因此,除非您的代码专门与远程处理有关,否则我建议不要使用[Synchronization].

So unless your code specifically has to do with remoting, I would advice against the use of [Synchronization].

这篇关于哪种方法最适合线程同步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆