Cefsharp第二次初始化会引发错误

时间:2017-04-03 17:07:44

标签: c# wpf chromium-embedded cefsharp

我的应用程序需要在请求时调用(屏幕外)浏览器并在完成后进行清理。

所以我创建了一个屏幕外浏览器

 public class OffScreenBrowser 
{
    private static ChromiumWebBrowser _browser;

    private static CefSettings _settings;

    public void Load(string url,System.Drawing.Size size)
    {
        if (Cef.IsInitialized) return;
        Init(new BrowserProcessHandler());

        _browser = new ChromiumWebBrowser(url) {Size = size};
        _browser.NewScreenshot += _browser_NewScreenshot;
    }
    public System.Windows.Controls.Image BrowserImage { get; set; }
    public Action NewScreenShotAction { get; set; }

    private void _browser_NewScreenshot(object sender, EventArgs e)
    {
        var bitmap = _browser.ScreenshotOrNull();
        Application.Current.Dispatcher.Invoke(new Action(() =>
        {
            using (MemoryStream memory = new MemoryStream())
            {
                bitmap.Save(memory, ImageFormat.Png);
                memory.Position = 0;
                BitmapImage bitmapImage = new BitmapImage();
                bitmapImage.BeginInit();
                bitmapImage.StreamSource = memory;
                bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
                bitmapImage.EndInit();

                BrowserImage = new System.Windows.Controls.Image() {Source = bitmapImage};
                NewScreenShotAction();
            }
        }));
    }

    public void Close()
    {
        _browser.NewScreenshot -= _browser_NewScreenshot;
        _browser.Dispose();
        _settings.Dispose();
        Cef.Shutdown();
    }

    public static void Init(IBrowserProcessHandler browserProcessHandler)
    {
        _settings = new CefSettings();
        if (!Cef.Initialize(_settings, true, browserProcessHandler))
            throw new Exception("Unable to Initialize Cef");
    }
}

想法是 - 单击按钮创建浏览器并单击另一个按钮关闭浏览器

private OffScreenBrowser offScreenBrowser;

private void OPen_OnClick(object sender, RoutedEventArgs e)
{
    var address = @"https://www.google.co.uk";
    var width = 200;
    var height = 100;
    var windowSize = new System.Drawing.Size(width, height);
     offScreenBrowser = new OffScreenBrowser();
    offScreenBrowser.Load(address, windowSize);

    offScreenBrowser.NewScreenShotAction = () => 
    {
        Browser.Content = offScreenBrowser.BrowserImage;
    };
}

private void Close_OnClick(object sender, RoutedEventArgs e)
{
    offScreenBrowser.Close();
}

第一次点击它一切正常。点击关闭时,似乎清理工作正常。

但是当我第二次点击打开按钮时,我得到一个例外,如下所示

"An unhandled exception of type 'System.AccessViolationException' occurred in CefSharp.Core.dll

Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt."

我做错了什么?

2 个答案:

答案 0 :(得分:0)

这是Chromium框架的局限性。

CEF每个进程只能被初始化/关闭一次, 有关更多详细信息,请参见Need to Know/Limitations,这是对底层Chromium框架的限制。

答案 1 :(得分:0)

要解决此问题,您可以在开始表单中调用Cef.Initialize,而只需在应用程序中调用一次 您可以在任何一种申请表中多次致电ChromiumWebBrowser 对我有用