一个关于Parallel和action的问题

阿浩No_1 2019-08-18 04:22:37
请教个问题,代码如下:
DataTable dt = GetPrice("SELECT distinct([StockCode]) FROM [MyStocks].[dbo].[StocksDayPrice] order by StockCode");
int datacount = dt.Rows.Count;

Stopwatch sw = new Stopwatch();
sw.Start();

int Arr_actionLength = 10;
int substep = datacount / Arr_actionLength;

int tail = datacount % Arr_actionLength;
if (tail != 0)
{
Arr_actionLength += 1;
}

Action[] actions = new Action[Arr_actionLength];

//****************问题就在这个for循环上************************//
for (int i = 0; i < Arr_actionLength; i++)
{
actions[i] = () =>
{
for (int j = (i * substep); j < ((i + 1) * substep); j++)
{
if (j >= datacount)
{
break;
}
updateTheAged("insert into test_parallel(stockcode) values('" + dt.Rows[j][0].ToString() + "')");
}
};
}
//**************************************//
Parallel.Invoke(actions);

这个for循环无法获取正常进行插入操作,但我将它换成
actions[0] = () =>
{
for (int j = 0 * substep; j < (0 + 1) * substep; j++)
{
if (j >= datacount)
{
break;
}
updateTheAged("insert into test_parallel(stockcode) values('" + dt.Rows[j][0].ToString() + "')");
}
};
.......
actions[10] = () =>
{
for (int j = 10 * substep; j < (10 + 1) * substep; j++)
{
if (j >= datacount)
{
break;
}
updateTheAged("insert into test_parallel(stockcode) values('" + dt.Rows[j][0].ToString() + "')");
}
};

又一切正常。运行结果也正常。搞不明白了,请假下大家。
...全文
83 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
阿浩No_1 2019-08-18
  • 打赏
  • 举报
回复
确实是这个问题
github_36000833 2019-08-18
  • 打赏
  • 举报
回复
错误捕获的例子:

var actions = new Action[3];
for(int i = 0; i < actions.Length; i++)
{
    actions[i] = () => Console.WriteLine("action:"+i);
}
actions[0](); // 输出action:3
actions[1](); // 输出action:3
actions[2](); // 输出action:3
github_36000833 2019-08-18
  • 打赏
  • 举报
回复
请注意这里我说的”i的引用“是一种形象的说法,不是严格意义上的引用。
github_36000833 2019-08-18
  • 打赏
  • 举报
回复
由于闭包捕获了并使用了i的引用,每个Action都错误地用了最后一个i。 一种解决方法,就是使用一个本地变量,作为每次循环中i的副本,这样闭包才使用每次循环中的正确值。 //****************问题就在这个for循环上************************// for (int i = 0; i < Arr_actionLength; i++) { var iCaptured = i; actions[i] = () => { for (int j = (iCaptured * substep); j < ((iCaptured + 1) * substep); j++) { if (j >= datacount) { break; } updateTheAged("insert into test_parallel(stockcode) values('" + dt.Rows[j][0].ToString() + "')"); } }; }

110,538

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧