相关疑难解决方法(0)

如何并行迭代动态值字典?

我试图使用dict中的值副本为每个循环生成线程.

我最初的理解是,这foreach将创造一个新的范围,并导致:

Dictionary<string, string> Dict = new Dictionary<string, string>() { { "sr1", "1" }, { "sr2", "2" } };
foreach (KeyValuePair<string, string> record in Dict) {
    new System.Threading.Timer(_ =>
    {
        Console.WriteLine(record.Value);
    }, null, TimeSpan.Zero, new TimeSpan(0, 0, 5));
}
Run Code Online (Sandbox Code Playgroud)

写道

1
2
2
2
Run Code Online (Sandbox Code Playgroud)

而不是(预期):

1
2
1
2
Run Code Online (Sandbox Code Playgroud)

所以我尝试在foreach中克隆kvp:

KeyValuePair<string, string> tmp = new KeyValuePair<string, string>(record.Key, record.Value);
Run Code Online (Sandbox Code Playgroud)

但这会产生相同的结果.

我也试过了,System.Parallel.ForEach但似乎需要非动态的价值,这对我的字典来说有点火车粉碎.

如何用线程迭代我的字典?

c# multithreading parallel.foreach

1
推荐指数
1
解决办法
1092
查看次数

标签 统计

c# ×1

multithreading ×1

parallel.foreach ×1