-2

我需要在管理进程队列的 Web 应用程序中创建一个类实例。此类内部有多个线程,用于查找队列并使用它。这样做的最佳理由是什么?

我已经应用了单例设计模式,但我不明白是否必须在其中创建静态或普通队列。有人可以给我一个例子吗?

解决方案

好的谢谢!这是我的单身课程:

    public sealed class MyWorkingSingletonClass
    {

    private static readonly ILog LOG = LogManager.GetLogger(typeof(MyWorkingSingletonClass));
    private static MyWorkingSingletonClass instanza;
    private static readonly object lockObject = new object();
    private static ConcurrentQueue<Process> syncCoda = new ConcurrentQueue<Process>();

    private MyWorkingSingletonClass()
    {
    }

    public static MyWorkingSingletonClass Instanza
    {
        get
        {
            lock (lockObject)
            {
                if (instanza == null)
                    instanza = new PdfDucumentConverter();
                return instanza;
            }
        }
    }



    public void AddProcess(Process p)
    {
        syncCoda.Enqueue(p);
    }

    public void Start()
    {
        Task.Factory.StartNew(WorkerTask2);
    }

    public static void WorkerTask2()
    {

        do
        {
            try
            {
                Process p;
                if (syncCoda.TryDequeue(out p))
                {
                    p.Start();
                    p.PriorityClass = ProcessPriorityClass.High;
                    p.WaitForExit();
                }
            }
            catch (Exception ex)
            {
                LOG.Error(ex);
            }
        } while (true);
    }

    }
4

1 回答 1

2

您需要实现新的单例类,它继承并发队列类,这是线程安全的队列,以确保它可以在多线程环境中工作:

public class SingletonConcurrentQueue<T> : ConcurrentQueue<T>
{
    private static readonly SingletonConcurrentQueue<T> 
                                   _instance = new SingletonConcurrentQueue<T>();

    static SingletonConcurrentQueue(){}
    private SingletonConcurrentQueue(){}

    public static SingletonConcurrentQueue<T> Instance
    {
        get { return _instance; }
    }
}
于 2012-09-29T15:06:49.690 回答