C# 多线程批量解析

标签 c# multithreading

我正在制作一个“网络解析器”,除了它仅适用于 1 个网站,它将同时解析许多不同的页面。

目前,我可能需要以相对较快的方式解析 300,000 个页面(我只抓取少量信息,不会花费太长时间,每个页面大约需要 3 秒我网络上的最大值)。当然,900,000 秒换算天数 = 10 天,这是非常糟糕的表现。我想最多将它减少到几个小时,我对请求数量的时间是合理的,但它仍然需要“快速”。我也知道我不能一次完成 300,000 个,否则网站会阻止我的所有请求,因此每个请求之间必须有几秒钟的延迟。

我目前在单个 foreach 循环中处理它,没有利用任何多线程,但我知道我可以利用它,我不确定我应该走哪条路,无论它是线程池,或其他类型的线程系统或设计。

基本上,我正在寻找有人为我指出使用多线程提高效率的正确方向,这样我就可以减少在我这边解析那么多页面、某种线程系统或结构所花费的时间。

谢谢

最佳答案

查看 this 的答案问题,听起来你可能想查看 Parallel.ForEach .

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

  1. 下载LINQPad . (应该是任何 C# 开发人员的先决条件,恕我直言!)
  2. 在“示例”中,“下载/导入更多示例...”并确保您已下载“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!

关于C# 多线程批量解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16549543/

相关文章:

c# - 等待 MoveTo 操作完成的正确方法是什么?

c# - Windows 事件查看器和 log4net

c# - Regex.Matches 没有捕获我需要的整个组

java - onPostExecute 没有被调用

c++ - 多线程应用程序中的显示任务必须使用原子锁或互斥锁吗?

c# - SQL错误关键字 'user'附近的语法不正确

c# - XmlDocument.Load 替换 ">"

python - 并行Python : 4 threads have same speed as 2 threads

java - 使用 PoolingClientConnectionManager 时释放连接?

c++ - 等待多个 future ?