我正在用 C# 编写一个应用程序,并且正在创建多个 BackgroundWorker 线程以从网页中获取信息。尽管他们是 BackgroundWorkers,但我的 GUI 表单变得没有响应。
调试时,程序无响应时暂停,可以看到我在主线程中,在网页抓取方法上暂停。不过,这个方法只能从新线程中调用,所以我不知道为什么我会出现在主线程中。
这有道理吗?我能做些什么来确保 Web 请求只在它们各自的线程中处理?
编辑:一些代码和解释
我正在处理大量地址。每个线程将处理一个或多个地址。我可以选择我想创建多少线程(我保持谦虚:))
//in “Controller” class
public void process()
{
for (int i = 1; i <= addressList.Count && i<= numthreads; i++)
{
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += doWork;
bw.RunWorkerAsync((object)i);
}
}
public void doWork(object sender, DoWorkEventArgs e)
{
//create an object that has the web fetching method, call it WorkObject
//WorkObject keeps a reference to Controller.
//When it is done getting information, it will send it to Controller to print
//generate a smaller list of addresses to work on, using e.Argument (should be 'i' from the above 'for' loop)
WorkObject.workingMethod()
}
创建 WorkObject 时,它使用“i”来知道它是什么线程号。它将使用它来获取要从中获取信息的网址列表(从主窗体、控制器和每个工作对象共享的较大地址列表中获取信息——每个线程将处理较小的地址列表)。当它遍历列表时,它将调用“getWebInfo”方法。
//in “WorkObject” class
public static WebRequest request;
public void workingMethod()
{
//iterate over the small list of addresses. For each one,
getWebInfo(address)
//process the info a bit...then
myController.print()
//note that this isn’t a simple “for” loop, it involves event handlers and threading
//Timers to make sure one is done before going on to the next
}
public string getWebInfo (string address)
{
request = WebRequest.Create(address);
WebResponse response = request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string content = reader.ReadToEnd();
return content;
}