StaTaskScheduler (TPL扩展)和WebBrowser控件WPF -错误线程
本文关键字:WPF 控件 错误 线程 WebBrowser TPL 扩展 StaTaskScheduler | 更新日期: 2023-09-27 18:05:11
我想下载一个网站与WebBrowser控件(WPF)在后台和解析网站之后。下载应该是一个"紧密循环"。我只需要源作为字符串。我尝试了下面的代码,没有给我的结果。如果我不使用它与StaTaskScheduler程序似乎冻结在循环期间。有什么想法吗?
谢谢
StaTaskScheduler sta = new StaTaskScheduler(numberOfThreads: 1);
private void Button1_Click(object sender, RoutedEventArgs e)
{
for (int i = 0; i < 2; i++)
{
Task.Factory.StartNew(() =>
{
WebBrowser wb3 = new WebBrowser();
wb3.Source = new Uri("MyURL");
n++;
wb3.LoadCompleted += new LoadCompletedEventHandler(wb_LoadCompleted);
}, CancellationToken.None, TaskCreationOptions.None, sta);
}
}
void wb_LoadCompleted(object sender, NavigationEventArgs e)
{
WebBrowser w = sender as WebBrowser;
HtmlDocument document = new HtmlDocument(w.Document);
blockingCollection.Add(document.Body.OuterHtml);
Task.Factory.StartNew(
() =>
{
while (!blockingCollection.IsCompleted)
{
string dlcode;
Thread.Sleep(500);
if (blockingCollection.TryTake(out dlcode))
{
// tb is a TextBox
Dispatcher.BeginInvoke(new Action(() => { tb.Text = dlcode; }));
}
}
}, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
}
我建议不要使用WebBrowser
,而是直接使用WebClient
。最简单的方法是编写一个例程,将下载数据封装在Task中:
Task<string> DownloadStringAsync(Uri address)
{
TaskCompletionSource<string> tcs = new TaskCompletionSource<string>();
WebClient client = new WebClient();
// Note that you can add error checking here by looking at e.Error/etc, and setting the cancel/error in tcs appropriately...
client.DownloadStringCompleted += (o,e) => tcs.SetResult(e.Result);
client.DownloadStringAsync(address);
return tcs.Task;
}
这样,您应该能够直接使用这些任务,并在完成时将它们的结果设置到BC中。这将比试图旋转WebBrowser
控件简单得多,这是为了视觉使用。