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

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

 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."


我究竟做错了什么?

最佳答案

这是Chromium框架的局限性。

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

09-07 01:45