C#中的线程:如何保持循环索引线程安全? [英] Threading in C#: How to keep loop-index thread-safe?

查看:242
本文介绍了C#中的线程:如何保持循环索引线程安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的示例中,似乎for循环的索引i由每个线程独立地修改,从而导致DoWork_Threaded()中的i的奇数值(多个,甚至大于System.Environment.ProcessorCount-1的值).

In the following example, it seems that the index i of the for-loop is modified independently by each thread leading to strange values of i (multiples, even values larger than System.Environment.ProcessorCount-1) in DoWork_Threaded()

如何在C#中正确完成多线程循环?

How are multithreaded loops properly done in C# ?

// Prepare all threads
Thread[] threads = new Thread[System.Environment.ProcessorCount];

// Start all threads
for (int i = 0; i < System.Environment.ProcessorCount; i++)
{
   threads[i] = new Thread(() => DoWork_Threaded(i));
   threads[i].Start();
}

// Wait for completion of all threads
for (int i = 0; i < System.Environment.ProcessorCount; i++)
{
   threads[i].Join();
}

推荐答案

首先,为什么不使用任务并行库而不是滚动自己的线程调度服务?它已经具有确定调度线程的处理器数量的逻辑.

First of all, rather than rolling your own thread scheduling service, why not use the task parallel library? It already has logic that determines the number of processors to schedule threads onto.

要回答您的实际问题,您正在关闭循环变量.请参阅我的文章,了解为什么这是错误的:

To answer your actual question, you are closing over a loop variable. See my article on why that is wrong:

https://ericlippert.com/2009/11/12/闭环考虑可变部分一/

简而言之:i变量和变量 change .当您的lambda执行时,它以 current i执行,而不是创建委托时曾经使用的值.

In short: i is a variable and variables change. When your lambda executes, it executes with the current value of i, not the value it used to have when the delegate was created.

这篇关于C#中的线程:如何保持循环索引线程安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆