Search code examples
c#executeblockingcollection

BlockingCollection auto executes my functions when I attempt to add them to list


            var tasks0 = new BlockingCollection<object>(new ConcurrentQueue<object>());
            tasks0.Add(Fetch(APCounter));
            tasks0.Add(Decode(APCounter));
            tasks0.Add(ALURes(APCounter));
            tasks0.Add(Memory(APCounter));
            tasks0.Add(WriteB(APCounter));


            var tasks1 = new BlockingCollection<object>(new ConcurrentQueue<object>());
            tasks1.Add(Fetch(APCounter+1));
            tasks1.Add(Decode(APCounter + 1));
            tasks1.Add(ALURes(APCounter + 1));
            tasks1.Add(Memory(APCounter + 1));
            tasks1.Add(WriteB(APCounter + 1));

I don't want it execute the functions being added now. I'll do that manually later using the business logic. !!!


Solution

  • As others have said, you'll need to store a list of Delegates, or something similar, to do what you want. You are executing those functions and then storing the result in a blocking collection. The first thing that you need to do is change the generic type on the blocking collection to:

    //add tasks
    //if the functions return a common object other than "object" then adjust this accordingly
    var tasks0 = new BlockingCollection<Func<object>>();//defaults to using a ConcurrentQueue
    tasks0.Add(()=>Fetch(APCounter));
    tasks0.Add(()=>Decode(APCounter));
    tasks0.Add(()=>ALURes(APCounter));
    tasks0.Add(()=>Memory(APCounter));
    tasks0.Add()=>(WriteB(APCounter));
    

    Then to actually execute the functions:

    //run tasks
    object firstResult = tasks0.Take()();
    object secondResult = tasks0.Take()();
    //...