How to create Singleton with async method?
I want to have an si开发者_StackOverflow中文版ngleton, 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?)
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)
{ /* ... */ }
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;
}
}
}
}
精彩评论