1

如何将时间点值传递或冻结给任务?

下面的代码的问题是传递给 DocFTSinXsCollection(SID) 的 SID 不是在执行 Task.Factory.StartNew 时,而是来自下一个 rdr.Read() 的 SID。

while (rdr.Read())
{
     SID = rdr.GetInt32(0);
     // other code
     Task.Factory.StartNew(() =>
     {
         // this often gets the new  SID - I need the SID from when Task was started
         DocFTSinXsCollection docFTSinXsCollection = new DocFTSinXsCollection(SID);
     }
     // other code
}
4

1 回答 1

1

您需要SID在循环中声明为局部变量,while以便每个闭包都有自己的变量:

while (rdr.Read())
{
     int SID = rdr.GetInt32(0);
     // other code
     Task.Factory.StartNew(() =>
     {
         // this often gets the new  SID - I need the SID from when Task was started
         DocFTSinXsCollection docFTSinXsCollection = new DocFTSinXsCollection(SID);
     }
     // other code
}
于 2012-09-02T01:11:55.367 回答