C# creating function queue

允我心安 提交于 2019-12-22 10:08:48

问题


I have written a class called QueueManager:

class QueueManager
{
    Queue functionsQueue;

    public bool IsEmpty 
    { 
        get 
            {
                if (functionsQueue.Count == 0)
                    return true;
                else
                    return false;
            }
    }

    public QueueManager()
    {
        functionsQueue = new Queue();
    }

    public bool Contains(Action action)
    {
        if (functionsQueue.Contains(action))
            return true;
        else 
            return false;
    }

    public Action Pop()
    {
        return functionsQueue.Dequeue() as Action;
    }

    public void Add(Action function)
    {
        functionsQueue.Enqueue(function);
    }

    public void Add(Func<CacheObject,Boolean> function)
    {
        functionsQueue.Enqueue(function);
    }

and when I create an instance of this class and call Add method it works fine for functions with no arguments, for example: functionQueue.Add(Method); , but when calling on methods that have an argument and return value(in my case ClassType as argument, and Boolean as return value), for example functionQueue.Add(Method2(classObject)); it does not compile, what am I missing?


回答1:


Because with functionQueue.Add(Method2(classObject)) you queue the result of your call, not the call itself.

To enqueue a method with parameters you should change the Add prototype to accept parameters (and store them together with the delegate). As alternative you can use lambdas:

functionQueue.Add(() => Method2(classObject));

(then your second overload of Add is useless, you can always queue an Action where you give all the parameters inside the closure).

Update
An example of a queue of this type is inside WinForms, dispatching of methods from other threads than the main thread is done with a method queue (look at the disassembly of Control.MarshaledInvoke). Skipping synchronization and contexts it keeps a System.Collections.Queue where each entry is ThreadMethodEntry (a structure used to hold needed data).



来源:https://stackoverflow.com/questions/10717344/c-sharp-creating-function-queue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!