我在这里发布了很多关于多线程的文章,伟大的stackoverflow社区帮助我理解了很多多线程。
我在网上看到的所有例子都只涉及一个线程。
我的申请是为一家保险公司(家族公司)工作。全部免费)。无论如何,用户能够选择他们想要运行的线程数。例如,假设用户希望应用程序一次抓取5个站点,然后在当天晚些时候,他选择了20个线程,因为他的计算机没有做任何其他事情,所以它有多余的资源。
基本上,应用程序构建了一个列表,比如说1000个要抓取的站点。一个线程开始执行此操作,并更新UI并构建列表。
完成后,将调用另一个线程来开始抓取。根据用户设置要使用的线程数量,它将创建x个线程。
创建这些线程的最佳方式是什么?我是否应该在列表中创建1000个线程。然后遍历它们?如果用户设置了5个线程运行,它将一次循环5个线程。
我理解线程,但它的应用程序逻辑让我着迷。
网上有什么想法或资源可以帮到我吗?
发布于 2010-02-08 23:53:28
为此,您可以考虑使用线程池:
using System;
using System.Threading;
public class Example
{
public static void Main()
{
ThreadPool.SetMaxThreads(100, 10);
// Queue the task.
ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc));
Console.WriteLine("Main thread does some work, then sleeps.");
Thread.Sleep(1000);
Console.WriteLine("Main thread exits.");
}
// This thread procedure performs the task.
static void ThreadProc(Object stateInfo)
{
Console.WriteLine("Hello from the thread pool.");
}
}发布于 2010-02-09 00:11:29
这个刮板,它运行的时候会占用很多CPU吗?
如果它与这1000个远程站点进行大量通信,下载它们的页面,这可能会花费比实际分析页面更多的时间。
您的用户有多少个CPU核心?如果它们有2个线程(这在最近很常见),那么超过两个同时执行分析的线程,它们不会看到任何速度的提高。
因此,您可能需要“并行化”页面的下载。我怀疑您是否需要对页面进行同样的分析。
看一下异步IO,而不是显式的多线程。它允许您并行启动一系列下载,然后在每个下载完成时进行回调。
发布于 2010-02-09 00:04:06
我认为这个例子基本上就是你需要的。
public class WebScraper
{
private readonly int totalThreads;
private readonly List<System.Threading.Thread> threads;
private readonly List<Exception> exceptions;
private readonly object locker = new object();
private volatile bool stop;
public WebScraper(int totalThreads)
{
this.totalThreads = totalThreads;
threads = new List<System.Threading.Thread>(totalThreads);
exceptions = new List<Exception>();
for (int i = 0; i < totalThreads; i++)
{
var thread = new System.Threading.Thread(Execute);
thread.IsBackground = true;
threads.Add(thread);
}
}
public void Start()
{
foreach (var thread in threads)
{
thread.Start();
}
}
public void Stop()
{
stop = true;
foreach (var thread in threads)
{
if (thread.IsAlive)
{
thread.Join();
}
}
}
private void Execute()
{
try
{
while (!stop)
{
// Scrap away!
}
}
catch (Exception ex)
{
lock (locker)
{
// You could have a thread checking this collection and
// reporting it as you see fit.
exceptions.Add(ex);
}
}
}
}https://stackoverflow.com/questions/2222778
复制相似问题