0

我正在我的应用程序中使用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

我找不到任何解决方案。

4

2 回答 2

4

项目源代码中的CefSharp.OffScreen.Example.Program.cs类包含一个使用TaskCompletionSource包装LoadingStateChanged事件的示例,以便您可以awaitPage 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.

于 2019-12-10T23:17:22.320 回答
0

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

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;
    }
}

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

于 2019-12-09T18:49:24.057 回答