Can't force CefSharp to load synchronously

I have an offscreen ChromiumWebBrowser

one that I use to run some JS on the page and get the results.

The Load method is synchronous, but I cannot run the JS code until the FrameLoadEnd event is raised, which means that either my targets. Loading is an asynchronous method that ends with the FrameLoadEnd event.

To make the code clearer, I tried to create an extension method that would allow me to wait for the page to load using await

instead of registering for an event. But when I use this method with TaskCompletionSource, the javascript that should run after the page is loaded doesn't load, but when used AutoResetEvent

and waited on, the code does work on it.

This code doesn't work:

public static Task LoadPageAsync(this IWebBrowser browser, string address)
{
    TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
    browser.FrameLoadEnd += (sender, args) =>
    {
        if (args.IsMainFrame)
        {
            tcs.TrySetResult(true);
        }
    };
    browser.Load(address);
    return tcs.Task;
}

      

And it does:

public static AutoResetEvent LoadPageAsync(this IWebBrowser browser, string address)
{
    AutoResetEvent are = new AutoResetEvent(false);
    browser.FrameLoadEnd += (sender, args) =>
    {
        if (args.IsMainFrame)
        {
            are.Set();
        }
    };
    browser.Load(address);
    return are;
}

      

This is the calling code:

await _browser.LoadPageAsync("Some web address");
LoadScripts();

DoJsThing();
GetJsData();

      

They do the same thing, but I feel like the purpose of the function is much clearer when returning a task than when returning an AutoResetEvent.

Why can't I use TaskCompletionSource to indicate that I am done? Am I doing something wrong?

+3


source to share


1 answer


Here is a basic example https://gist.github.com/amaitland/40394439ddefdf4e66b7



Note. I used NavStateChanged

it as this is the best indicator of when the entire page has finished loading.

+5


source







All Articles