【发布时间】:2011-01-01 00:26:36
【问题描述】:
我正在创建一个应用程序,使用以下方法对网站进行屏幕截图http://pietschsoft.com/post/2008/07/C-Generate-WebPage-Thumbmail-Screenshot-Image.aspx
我试图使应用程序多线程,但我遇到了以下错误:
[ActiveX 控件 '8856f961-340a-11d0-a96b-00c04fd705a2' 无法实例化,因为当前线程不在单线程单元中。]
有什么建议可以解决这个问题吗?我的代码基本如下:
List<string> lststrWebSites = new List<string>();
lststrWebSites.Add("http://stackoverflow.com");
lststrWebSites.Add("http://www.cnn.com");
foreach (string strWebSite in lststrWebSites)
{
System.Threading.ThreadStart objThreadStart = delegate
{
Bitmap bmpScreen = GenerateScreenshot(strWebSite, -1, -1);
bmpScreen.Save(@"C:\" + strWebSite + ".png",
System.Drawing.Imaging.ImageFormat.Png);
};
new System.Threading.Thread(objThreadStart).Start();
}
GenerateScreenShot() 函数实现是从上面的 URL 复制过来的:
public Bitmap GenerateScreenshot(string url)
{
// This method gets a screenshot of the webpage
// rendered at its full size (height and width)
return GenerateScreenshot(url, -1, -1);
}
public Bitmap GenerateScreenshot(string url, int width, int height)
{
// Load the webpage into a WebBrowser control
WebBrowser wb = new WebBrowser();
wb.ScrollBarsEnabled = false;
wb.ScriptErrorsSuppressed = true;
wb.Navigate(url);
while (wb.ReadyState != WebBrowserReadyState.Complete)
{ Application.DoEvents(); }
// Set the size of the WebBrowser control
wb.Width = width;
wb.Height = height;
if (width == -1)
{
// Take Screenshot of the web pages full width
wb.Width = wb.Document.Body.ScrollRectangle.Width;
}
if (height == -1)
{
// Take Screenshot of the web pages full height
wb.Height = wb.Document.Body.ScrollRectangle.Height;
}
// Get a Bitmap representation of the webpage as it's rendered in
// the WebBrowser control
Bitmap bitmap = new Bitmap(wb.Width, wb.Height);
wb.DrawToBitmap(bitmap, new Rectangle(0, 0, wb.Width, wb.Height));
wb.Dispose();
return bitmap;
}
【问题讨论】:
-
我对您尝试在非 GUI 线程中创建和操作浏览器控件感到有些困惑。您是否有可能将繁重的工作与将繁重的工作委派给工作线程的控件的交互分开?
-
好吧,我试图这样做,但我卡住了。
标签: c# multithreading webbrowser-control