多种形式,只需一次初始化

时间:2019-02-12 15:49:37

标签: cefsharp chromium-embedded

我想遍历一系列凭证,并为每个凭证启动一个托管Chrome浏览器的表单的新实例。第一种形式可以完美工作,第二种形式(及后续形式)悬挂在新的铬鼓风机上。

从发起方调用的代码

        var cef_settings = InitCef();

        logger.Info($"Chromium: '{CefSharp.Cef.ChromiumVersion}', CEF: '{CefSharp.Cef.CefVersion}', CefSharp: '{CefSharp.Cef.CefSharpVersion}', BrowserSubprocessPath: '{cef_settings.BrowserSubprocessPath}'.");
        foreach (var okta in creds)
        {
            logger.Info($"Running with username: {okta.Username}");

            using (var MyForm = new FrmScraper(okta, client))
            {
                Application.Run(MyForm);
            }
        }
        CefSharp.Cef.Shutdown();

代码形式

    private void FrmScraper_FormClosing(object sender, FormClosingEventArgs e)
    {
        Logger.Trace(string.Format("FrmScraper_FormClosing: Started, Reason: '{0}'", e.CloseReason.ToString()));
        if (chromeBrowser != null)
        {
            chromeBrowser.LoadingStateChanged -= ChromeBrowser_LoadingStateChanged;
            chromeBrowser.ConsoleMessage -= ChromeBrowser_ConsoleMessage;
            if (Controls.Contains(chromeBrowser))
                Controls.Remove(chromeBrowser);
            chromeBrowser.Dispose();
            chromeBrowser = null;
        }
        Logger.Trace("FrmScraper_FormClosing: GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);");
        GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);

        Logger.Trace("FrmScraper_FormClosing: Calling GC.WaitForPendingFinalizers();");
        GC.WaitForPendingFinalizers();

        Logger.Trace("FrmScraper_FormClosing: Ended");
    }

从Form_Load调用

    private void InitializeChromium(string Address)
    {
        Logger.Trace("InitializeChromium: Started");

        Logger.Trace("InitializeChromium: Step 1");
        var requestContextSettings = new RequestContextSettings
        {
            CachePath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "GenesysCustomerCare", DateTime.Now.ToString("yyyy-MM-dd"), Guid.NewGuid().ToString("d"))
        };
        var requestContext = new RequestContext(requestContextSettings);
        Logger.Trace($"InitializeChromium: CachePath: '{requestContextSettings.CachePath}'.");
        Logger.Trace("InitializeChromium: Step 2");

        // Create a browser component
        // This is the line that hangs on subsequent runs.
        chromeBrowser = new ChromiumWebBrowser(Address)
        {
            RequestContext = requestContext
        };
        Logger.Trace("InitializeChromium: Step 3");

        // Add it to the form and fill it to the form window.
        Controls.Add(chromeBrowser);
        Logger.Trace("InitializeChromium: Step 4");
        chromeBrowser.Dock = DockStyle.Fill;
        chromeBrowser.LoadingStateChanged += ChromeBrowser_LoadingStateChanged;
        chromeBrowser.ConsoleMessage += ChromeBrowser_ConsoleMessage;
        Logger.Trace("InitializeChromium: Ended");
    }

0 个答案:

没有答案