如何使用异步方法创建Singleton?

时间:2011-04-25 22:04:37

标签: c#

我想要一个单身,比如说Printer,用一种方法,比如bool addToPrintQueue(Document document)addToPrintQueue应为异步(应立即返回),如果已添加到队列,则返回true;如果文档已在false中,则返回queue。如何编写这样的方法以及我应该使用什么来进行queue处理? (它应该是单独的线程吗?)

2 个答案:

答案 0 :(得分:0)

不确定为什么你需要一个单例,一个带锁定的异步线程应该在这里做得很好

 // create a document queue
    private static Queue<string> docQueue = new Queue<string>();

    // create async caller and result handler
    IAsyncResult docAdded = null;
    public delegate bool AsyncMethodCaller(string doc);

    // 
    public void Start()
    {
        // create a dummy doc
        string doc = "test";

        // start the async method
        AsyncMethodCaller runfirstCaller = new AsyncMethodCaller(DoWork);
        docAdded = runfirstCaller.BeginInvoke(doc,null,null);
        docAdded.AsyncWaitHandle.WaitOne();

        // get the result
        bool b = runfirstCaller.EndInvoke(docAdded);
    }


    // add the document to the queue
    bool DoWork(string doc)
    {

        lock (docQueue)
        {
            if (docQueue.Contains(doc))
            {
                return false;
            }
            else
            {
                docQueue.Enqueue(doc);
                return true;
            }
        }
    }
}

答案 1 :(得分:0)

您是否考虑过Event-based Async pattern。由于每个异步事件都有相应的已完成事件,该事件在方法完成时引发。这将告诉文档是否已添加到队列或失败。

我会创建Printer.addToPrintQueue事件并让订阅者订阅它。

printer.addToPrintQueueCompleted += _addToPrinterQueueCompleted;
printer.addToPrintQueueAsync();


private void _addToPrinterQueueCompleted(object sender, addToPrintQueueCompletedEventArgs e)
{ /* ... */ }