简体   繁体   中英

How to create Singleton with async method?

I want to have an singleton, say Printer , with one method, say bool addToPrintQueue(Document document) . addToPrintQueue should be async (should return immediately), return true if added to queue and false if document already in queue . How to write such method and what should I use for queue processing? (should it be separate thread?)

Not really sure why you need a singleton here, an asynchronous thread with locking should do just fine here

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

Have you consider doing Event-based Async pattern . Since each asynchronous event has corresponding completed event that is raised when the method finishes. This will tell if document is added to queue or it failed.

I would create Printer.addToPrintQueue event and let subscribers subscribe to it.

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


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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