相关疑难解决方法(0)

线程安全C#单例模式

我对这里记录的单例模式有一些疑问:http: //msdn.microsoft.com/en-us/library/ff650316.aspx

以下代码是文章的摘录:

using System;

public sealed class Singleton
{
   private static volatile Singleton instance;
   private static object syncRoot = new object();

   private Singleton() {}

   public static Singleton Instance
   {
      get 
      {
         if (instance == null) 
         {
            lock (syncRoot) 
            {
               if (instance == null) 
                  instance = new Singleton();
            }
         }

         return instance;
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

具体来说,在上面的例子中,是否需要在锁之前和之后将实例与null进行两次比较?这有必要吗?为什么不先执行锁定并进行比较?

简化以下是否有问题?

   public static Singleton Instance
   {
      get 
      {
        lock (syncRoot) 
        {
           if (instance == null) 
              instance = new Singleton();
        }

         return instance; …
Run Code Online (Sandbox Code Playgroud)

c# singleton design-patterns

74
推荐指数
5
解决办法
11万
查看次数

Parallel For不会在静态构造函数中导致死锁吗?

我试图将线程添加到我所拥有的静态类中,并遇到了一堆问题.我读了这个帖子和它链接到的博客文章,我想我明白了发生了什么.但我无法弄清楚为什么Parallel For循环仍然像在这个例子中那样工作:

using System;
using System.Threading;
using System.Threading.Tasks; 

namespace ThreadingTest
{
    public static class TestClass
    {
        public static int AwesomeNum = 43; 

        static TestClass()
        {
            string[] x = { "deal", "witch", "panda"};

            //does not cause a deadlock? huh?
            Parallel.For(0, x.Length,  i =>
                {
                    Console.WriteLine(x[i]); 
                });

            //results in a deadlock
            //Parallel.Invoke(writesomething, writesomethingelse); 

            //results in deadlock
            Thread thread = new Thread(new ThreadStart(() =>
            {
                Console.WriteLine("there is a bear in my soup"); 
            }));

            thread.Start();
            thread.Join(); 
        }

        private static void writesomething()
        { …
Run Code Online (Sandbox Code Playgroud)

.net c# multithreading

2
推荐指数
1
解决办法
491
查看次数

标签 统计

c# ×2

.net ×1

design-patterns ×1

multithreading ×1

singleton ×1