C#多线程质量分析

sl1*_*133 3 c# multithreading

我有点像'网络解析器',除了它只是一个网站,它将一次解析许多不同的页面.

目前,我需要以相对快速的方式解析300,000个页面(我只抓取了一小部分不需要太长时间才能完成的信息,每个页面最多花费约3秒钟网络).当然,900,000秒到天= 10天,这是可怕的表现.我想将此减少到最多几个小时,我对于请求数量的时间是合理的,但它仍然需要"快速".我也知道我不能一次只做300,000,或者网站会阻止我的所有请求,所以每次请求之间都要有几秒钟的延迟.

我目前在单个foreach循环中处理它,没有利用任何多线程,但我知道我可以利用它,我不知道我应该采取什么样的路径,无论是线程池,还是其他螺纹系统或设计的类型.

基本上,我正在寻找有人使用多线程向我指出正确的效率方向,这样我就可以轻松地解析我最终解析那么多页面的时间,某种系统或结构用于线程化.

谢谢

Moo*_*ice 7

看看这个问题的答案,因为听起来你可能想看看Parallel.ForEach.

还有其他各种方法可以以多线程方式实现您想要做的事情.让自己了解这是如何工作的:

  1. 下载LINQPad.(应该是任何C#开发人员的先决条件,imho!)
  2. 在"Samples","下载/导入更多样本......"中,确保已下载"C#中的异步函数".
  3. 完成样本,看看它们如何组合在一起.

实际上,这是与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!
Run Code Online (Sandbox Code Playgroud)