2014-07-11 197 views
-1

我希望将两个BlockingCollection<>传递给任务。我试图把它们放在一个对象数组中并传递它们,但它不起作用。谁能帮我这个?在那里我试图值传递的代码如下记载:将多个参数传递给任务

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 
     }); 
} 
+0

var lines = lineHolders [0]; – terrybozzio

+0

特定任务的BlockingCollection行取决于循环索引处理器。不能做一个lineHolders [0]。 – displayName

+0

什么是编译器错误? – Stefan

回答

2

您使用的是following超载StartNew的:

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

因为它只是不能应用索引上的对象它。投它,它会正常工作。

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 
       }); 
     } 
+0

你是否需要捕获一个循环内部的局部变量或仅仅是循环变量本身?我的理解是,如果你在StartNew中引用了处理器,那么你会得到对变化的循环变量的引用,并且结果将是意想不到的。但是循环内的本地代码如何处理?如果在处理器= 0时捕获对myLineHolder的引用,那么下一次在循环中引用同一个变量?当然不是? – user2981639