-1

I wish to pass two BlockingCollection<>s to a task. I tried to put them in an object array and pass them but it doesn't work. Can anyone help me with this? The code where i am trying to pass the values is written below:

var lineHolders = new[]
{
     new BlockingCollection<string>(linesCapacity),
     new BlockingCollection<string>(linesCapacity),
     new BlockingCollection<string>(linesCapacity),
     new BlockingCollection<string>(linesCapacity)
};

var chunksHolder = new[]
{
     new BlockingCollection<List<BsonDocument>>(chunksCapacity),
     new BlockingCollection<List<BsonDocument>>(chunksCapacity)
};

for (var processors = 0; processors < 16; processors++)
{
      var myLineHolder = lineHolders[processors%lineHolders.Length];
      var myChunkHolder = chunksHolder[processors%chunksHolder.Length];
      processorTaskArray[processors] = Task.Factory.StartNew((arg) =>
      {
          var lines = (BlockingCollection<string>) arg[0];  // compiler generates error here
          var chunks = (BlockingCollection<List<BsonDocument>>) arg[1]; // compiler generates error here

          // perform my work...


      },
      new object []
      {
          myLineHolder, 
          myChunkHolder
      });
}
displayName
  • 13,888
  • 8
  • 60
  • 75

1 Answers1

2

You're using the following overload of StartNew:

public Task StartNew(
    Action<Object> action,
    Object state
)

Since it's just an object you can't apply indexing on it. Cast it and it will work fine.

for (var processors = 0; processors < 16; processors++)
        {
            var myLineHolder = lineHolders[processors % lineHolders.Length];
            var myChunkHolder = chunksHolder[processors % chunksHolder.Length];
            processorTaskArray[processors] = Task.Factory.StartNew((arg) =>
            {
                var properArg = (object[]) arg;
                var lines = (BlockingCollection<string>) properArg[0]; // compiler generates error here
                var chunks = (BlockingCollection<List<BsonDocument>>) properArg[1]; // compiler generates error here

                // perform my work...

            },
            new object[]
              {
                  myLineHolder, 
                  myChunkHolder
              });
        }
Marcin Waligora
  • 548
  • 4
  • 11
  • Do you need to capture local variables inside a loop or just the loop variable itself? My understanding is if you referenced processors in the StartNew you'd get a reference to the changing loop variable and results would be unexpected. But what about the locals inside the loop - if you capture a reference to myLineHolder when processors = 0 is that a reference to the same variable next time around the loop? Surely not? – David Waterworth Oct 07 '15 at 21:02