查看此问题的答案,因为听起来您可能想查看Parallel.ForEach
.
还有各种其他方法可以以多线程方式实现您想要做的事情。为了让自己了解这是如何工作的:
- 下载LINQPad。(应该是任何 C# 开发人员的先决条件,恕我直言!)
- 在“示例”中,“下载/导入更多示例...”并确保您已下载“C# 中的异步函数”。
- 研究这些样本,看看它们是如何组合在一起的。
事实上,这里是使用 Uris 的异步示例之一:
// The await keyword is really useful when you want to run something in a loop. For instance:
string[] uris =
{
"http://linqpad.net",
"http://linqpad.net/downloadglyph.png",
"http://linqpad.net/linqpadscreen.png",
"http://linqpad.net/linqpadmed.png",
};
// Try doing the following without the await keyword!
int totalLength = 0;
foreach (string uri in uris)
{
string html = await (new WebClient().DownloadStringTaskAsync (new Uri (uri)));
totalLength += html.Length;
}
totalLength.Dump();
// The continuation is not just 'totalLength += html.Length', but the rest of the loop! (And that final
// call to 'totalLength.Dump()' at the end.)
// Logically, execution EXITS THE METHOD and RETURNS TO THE CALLER upon reaching the await statement. Rather
// like a 'yield return' (in fact, the compiler uses the same state-machine engine to rewrite asynchronous
// functions as it does iterators).
//
// When the task completes, the continuation kicks off and execution jumps back into the middle of the
// loop - right where it left off!