繁体   English   中英

单例多线程

[英]Multi Threading with Singletons

我正在为集中式服务器开发“打印队列”,该服务器负责根据需要将打印作业定向到其他服务器。

我作为具有“打印”端点的WCF服务来执行此操作。 一切都很好,我已经进行了设置,但是我试图开发一个线程安全的端点,该端点还可以返回排队的线程数的计数。

下面是一个示例类,该类触发多个线程并将其发送到“ Print”方法(该方法模拟多个人同时到达终点的行为)

public class ThreadStuff
{
    #region [Singleton Logic]

    private static ThreadStuff _instance;

    private ThreadStuff() { }

    private static ThreadStuff Instance
    {
        get { return _instance ?? (_instance = new ThreadStuff()); }
    }

    #endregion

    private static readonly object LockObject = new object();
    private int _queuedThreads;

    public static int QueuedThreads
    {
        get { return Instance._queuedThreads; }
    }

    public static void Start()
    {
        var threads = new Thread[10];
        for (var i = 0; i < 10; i++)
        {
            var threadNumber = i;
            var t = new Thread(() => Instance.MyMethod(threadNumber));
            threads[i] = t;
        }
        for (var i = 0; i < 10; i++)
        {
            var threadNumber = i;
            Thread.Sleep(50);
            threads[i].Start();
            Console.WriteLine("Thread {0} started", threadNumber);
        }

        Console.ReadKey();
    }

    private void MyMethod(int threadNumber)
    {
        Console.WriteLine("Thread {0} entered MyMethod", threadNumber);
        Instance._queuedThreads++;

        lock (LockObject)
        {
            Console.WriteLine("Thread {0} entered MyMethod's Lock", threadNumber);
            Thread.Sleep(2000);
            Console.WriteLine("Thread {0} finished Thread.Sleep", threadNumber);
        }

        Instance._queuedThreads--;
        Console.WriteLine("Thread {0} exited MyMethod", threadNumber);
    }
}

这按预期工作,并产生了以下结果:

但是,然后我在解决方案中添加了另一个项目,该项目将访问此单例的“ QueuedThreads”属性(模拟轮询端点的行为)。

该项目是一个简单的胜利表单应用程序,带有以下代码

textBox1.Text = ThreadStuff.QueuedThreads.ToString(CultureInfo.InvariantCulture);

但是,它始终返回0,winforms应用程序看不到“ ThreadStuff”类的Singleton数据,它创建了一个新的ThreadStuff实例。 我已经在办公室这一次ping通了,没有人知道为什么会这样,经过多次Google搜索后,我决定在这里询问。

任何帮助将不胜感激

试试这个模式:

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;
      }
   }
}

这种情况可能是因为它是2个不同的进程,一个控制台应用程序和一个WinForm应用程序。 只要是这种情况,您就需要某种类际通讯,以使WinForm应用程序能够查看排队的请求。 有几种方法可以做到这一点。 几种可能性

  • 将值存储在数据库中,然后在WinForm应用程序中从中读取
  • 使用消息队列/总线并发布WinForm应用程序侦听的消息
  • 命名管道
  • 插座

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM