Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typo3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何使用异步方法创建Singleton?_C# - Fatal编程技术网

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

C# 如何使用异步方法创建Singleton?,c#,C#,我想要一个单例,比如说Printer,有一个方法,比如说bool addToPrintQueue(Document Document)addToPrintQueue应该是异步的(应该立即返回),如果添加到队列中,则返回true;如果文档已经在队列中,则返回false。如何编写这样的方法,我应该使用什么进行queue处理?(它应该是单独的线程吗?不太清楚为什么这里需要一个单例,一个带锁的异步线程在这里就可以了 // create a document queue private stat

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

不太清楚为什么这里需要一个单例,一个带锁的异步线程在这里就可以了

 // 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;
            }
        }
    }
}
//创建文档队列
私有静态队列docQueue=新队列();
//创建异步调用程序和结果处理程序
IAsyncResult docAdded=null;
公共委托bool asynchmethodcaller(字符串文档);
// 
公开作废开始()
{
//创建一个虚拟文档
字符串doc=“test”;
//启动异步方法
AsyncMethodCaller runfirstCaller=新的AsyncMethodCaller(DoWork);
docAdded=runfirstCaller.BeginInvoke(doc,null,null);
docAdded.AsyncWaitHandle.WaitOne();
//得到结果
bool b=runfirstCaller.EndInvoke(docAdded);
}
//将文档添加到队列中
bool DoWork(字符串文档)
{
锁(docQueue)
{
if(docQueue.Contains(doc))
{
返回false;
}
其他的
{
docQueue.Enqueue(doc);
返回true;
}
}
}
}
你考虑做什么了吗?因为每个异步事件都有相应的已完成事件,该事件在方法完成时引发。这将告诉您是将文档添加到队列中还是失败

我将创建
Printer.addToPrintQueue
事件,并让订阅者订阅它

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


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

docQueue
不应该是私有的吗?应该是-我从以前编写的一些代码中复制了大部分内容,在这种情况下,队列需要是公共的,我只是在这个例子中没有注意到它