在C#中使用多线程加快循环(问题) [英] Speed up loop using multithreading in C# (Question)
问题描述
想象我有经过一百万/十亿串并检查他们中的水木清华功能
Imagine I have an function which goes through one million/billion strings and checks smth in them.
f.ex:
foreach (String item in ListOfStrings)
{
result.add(CalculateSmth(item));
}
它消耗的时间很多的,因为CalculateSmth是非常耗时的功能。
it consumes lot's of time, because CalculateSmth is very time consuming function.
我要问:如何在多线程融入这个过程有点儿
I want to ask: how to integrate multithreading in this kinda process?
f.ex:我想火-UP 5个线程和他们每个人返回了一定的效果,并且那去,直到上的列表中有项目。
f.ex: I want to fire-up 5 threads and each of them returns some results, and thats goes-on till the list has items.
也许任何人都可以显示一些例子或文章..
Maybe anyone can show some examples or articles..
忘了提,我需要它在.NET 2.0
Forgot to mention I need it in .NET 2.0
推荐答案
您可以尝试并行扩展
这允许你写的东西,如:
These allow you to write something like:
Parallel.Foreach (ListOfStrings, (item) =>
result.add(CalculateSmth(item));
);
当然result.add需要线程安全的。
Of course result.add would need to be thread safe.
这篇关于在C#中使用多线程加快循环(问题)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!