CefSharp winfoms 页面加载和等待

CefSharp winfoms Page load and wait

我正在处理我的应用程序中的 Cefsharp Offscreen。文档中提供的用于加载页面的代码是:

 const string testUrl = "https://github.com/cefsharp/CefSharp/wiki/Quick-Start";
  var settings = new CefSettings()
        {
   //By default CefSharp will use an in-memory cache, you need to specify a Cache Folder to persist data
   CachePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "CefSharp\Cache")
        };

   //Perform dependency check to make sure all relevant resources are in our output directory.
   Cef.Initialize(settings, performDependencyCheck: true, browserProcessHandler: null);

   // Create the offscreen Chromium browser.
   browser = new ChromiumWebBrowser(testUrl);

   // An event that is fired when the first page is finished loading.
   // This returns to us from another thread.
   browser.LoadingStateChanged += BrowserLoadingStateChanged;
   Cef.Shutdown();

但我想要那样的东西

browser = new ChromiumWebBrowser(); //without testUrl
 // and then 
browser.Load(testUrl).Wait();// and wait something like that;
// load url and wait unit page is fully loaded then go to next line

我找不到任何解决方案。

您必须设置一个标志并等待该标志。

private bool flag = false;

private void some_function(){

    browser = new ChromiumWebBrowser(); //without testUrl
    browser.Load(testUrl);
    browser.LoadingStateChanged += BrowserLoadingStateChanged;

    while(!flag)
    {
        Thread.Sleep(100);
    }
}
private void LoadingStateChanged(object sender, LoadingStateChangedEventArgs e)
{
    if (!e.IsLoading)
    {
        flag = true;
    }
}

这段代码看起来很无聊。但是你可以封装一个chromium浏览器。也许你可以使用单例模式。并实现等待功能。

CefSharp.OffScreen.Example.Program.cs class in the project source contains an example of using a TaskCompletionSource 包装 LoadingStateChanged 事件,这样您就可以 await Page Load

作为扩展方法实现的基本示例如下所示:

public static class WebBrowserExtensions
{
    public static Task LoadPageAsync(this IWebBrowser browser, string address = null)
    {
        var tcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);

        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;
                //Important that the continuation runs async using TaskCreationOptions.RunContinuationsAsynchronously
                tcs.TrySetResult(true);
            }
        };

        browser.LoadingStateChanged += handler;

        if (!string.IsNullOrEmpty(address))
        {
            browser.Load(address);
        }

        return tcs.Task;
    }
}

然后你可以写这样的代码

browser = new ChromiumWebBrowser();
await browser.LoadPageAsync(testUrl);

浏览器被编写为 async,不推荐也不支持使用 Task.Wait 进行阻止。使用 async/await.