Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# creating function queue

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?

like image 835
Fazi Avatar asked Dec 13 '22 02:12

Fazi


1 Answers

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).

like image 152
Adriano Repetti Avatar answered Dec 24 '22 03:12

Adriano Repetti