多线程环境中的C#Webbrowser控件

时间:2016-09-02 09:06:29

标签: c# multithreading webbrowser-control

我可以在单线程Env中运行WebBrowser

但是我无法在多线程env中运行它抛出访问冲突错误。

我正在尝试运行mutliple webbrowser实例,然后截取屏幕截图。

请查看随附的代码。

public class Image
{
    public int id { get; set; }
    public string url { get; set; }

}

internal class RenderMultipleImages
{

    //Sample Urls which contains Ajax Calls
    private static readonly List<Image> images = new List<Image>()
    {
       new Image(){id=1, url="www.abc1.com"},
       new Image() {id=2,url= "www.abc2.com"},
       new Image() {id=3,url= "www.abc3.com"},
       new Image() {id=4,url= "www.abc4.com"},
       new Image() {id=5, url="www.abc5.com"},
       new Image() {id=6,url= "www.abc6.com"}
    };

    private static int _imageWidth = 1200;
    private static int _imageHeight = 800;


    public static void Render()
    {
        var startTime = DateTime.UtcNow;

        var tasks = new List<Task>();
        for (var i = 0; i < images.Count; i++)
        {
            var i1 = i;
            var task = Task.Factory.StartNew(() => InvokeGenerateImage(images[i1].id, images[i1].url));
            tasks.Add(task);

        }
        Task.WaitAll(tasks.ToArray());
        Console.WriteLine("Time taken to finish: {0}", (DateTime.UtcNow - startTime).TotalSeconds);
    }

    private static void InvokeGenerateImage(int instanceNumber, string url)
    {
        var thread = new Thread(() => GenerateImage(instanceNumber, url));
        thread.SetApartmentState(ApartmentState.STA);
        thread.Start();
        thread.Join();
    }
    //[STAThread]
    private static void GenerateImage(int instanceNumber, string url)
    {
        Console.WriteLine("Started instance number: {0}", instanceNumber);

        var browser = new WebBrowser
        {
            ScrollBarsEnabled = false,
            ScriptErrorsSuppressed = true,
            Width = _imageWidth,
            Height = _imageHeight
        };
        browser.Navigate(url);

        while (browser.ReadyState != WebBrowserReadyState.Complete)
        {
            Application.DoEvents();
        }

        //As the url contains ajax calls am checking for the element id which tells us document loaded 
        while (browser.Document != null && browser.Document.GetElementById("chart-1") == null)
        {
            Application.DoEvents();
        }

        //Then screenshot
        saveScreeshot(browser, instanceNumber);

        browser.Dispose();

        Console.WriteLine("Finished instance number: {0}", instanceNumber);
    }

    static void saveScreeshot(WebBrowser webb,int instance)
    {
        Bitmap bitmap = new Bitmap(1024, 768);
        Rectangle bitmapRect = new Rectangle(0, 0, 1024, 768);
        webb.Size = new Size(1024, 768);
        webb.DrawToBitmap(bitmap, bitmapRect);
        var name = instance + ".png";
        bitmap.Save(name, ImageFormat.Png);
        bitmap.Dispose();
    }


}

}`

0 个答案:

没有答案