0

我编写了一个共享库,它使用 CefSharp.Offscreen 来完成 html 检索工作。当控制台应用程序调用它时它工作正常。但是当一个 WinForm 应用连接它时,在执行 tcs.TrySetResult(true) 之后,它并没有像在控制台应用中那样跳转到 await browser.GetSourceAsync()。

在 WinForm App 中,如果没有创建任何 UI 元素并且不在 UI 构造函数中,它可能会成功,但如果我在调用共享库之前创建 UI 元素,它总是会失败。

以另一种方式,我强制调用“var source = await browser.GetSourceAsync();” 获取当前的 html 源代码,但在 WinForm 连接中仍然没有响应。

        [STAThread]
        static void Main()
        {
            // I can put the init code here, but it does not help
            //CefSimpleLib.CefTest.Initialize();

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            TextBox tb = new TextBox(); // this blocks below call
            CefSimpleLib.CefTest cf = new CefSimpleLib.CefTest();

            Application.Run(new FormMain());
            //CefSimpleLib.CefTest.UnInitialize();
        }


namespace CefSimpleLib
{
    public class CefTest
    {
        public CefTest()
        {
            // You need to replace this with your own call to Cef.Initialize();
            // Default is to use an InMemory cache, set CachePath to persist cache

            Cef.Initialize(new CefSettings { CachePath = "cache" });

            MainAsync();

            System.Threading.Thread.Sleep(1000 * 1000);

            Cef.Shutdown();

        }

        private async void MainAsync()
        {
            var browserSettings = new BrowserSettings();
            //Reduce rendering speed to one frame per second, tweak this to whatever suites you best
            browserSettings.WindowlessFrameRate = 1;

            using (var browser = new ChromiumWebBrowser("https://www.baidu.com", browserSettings))
            {
                await LoadPageAsync(browser);
                var source = await browser.GetSourceAsync();


                await Task.Delay(10);
            }
        }

        public Task LoadPageAsync(IWebBrowser browser)
        {
            var tcs = new TaskCompletionSource<bool>();

            EventHandler<LoadingStateChangedEventArgs> handler = null;
            handler = (sender, args) =>
            {
                //Wait for while page to finish loading not just the first frame
                if (!args.IsLoading)
                {
                    browser.LoadingStateChanged -= handler;
                    tcs.TrySetResult(true);
                }
            };

            browser.LoadingStateChanged += handler;

            return tcs.Task;
        }
    }
}
4

0 回答 0