0

I was using Cefsharp Winforms, and recently I've been trying to switch to Offscreen. Everything works just fine, except now my code doesn't wait for EvaluateScriptAsync to complete before returns the page's source.

Or maybe I am just not quite understand how this task thing is working. Here is my progress so far:

private static void WebBrowserFrameLoadEnded(object sender, FrameLoadEndEventArgs e)
{
    var browser = (CefSharp.OffScreen.ChromiumWebBrowser)sender;

    if (e.Frame.IsMain)
    {
        browser.FrameLoadEnd -= WebBrowserFrameLoadEnded;

        var x = browser.EvaluateScriptAsync("/* some javascript codes */");

        if (x.IsCompleted && x.Result.Success)
        {
            x.ContinueWith(a =>
            {
                var task = browser.GetSourceAsync();

                task.ContinueWith(d =>
                {
                    if (d.IsCompleted)
                    {
                        globalRtnVal = d.Result;
                    }
                }).ConfigureAwait(false);
            });
        }
    }
}

And my main code is like this:

/* some codes */

CefSharp.OffScreen.ChromiumWebBrowser asd = new CefSharp.OffScreen.ChromiumWebBrowser(/* url */);
asd.BrowserSettings.Javascript = CefSharp.CefState.Enabled;
asd.BrowserSettings.WebSecurity = CefSharp.CefState.Disabled;

asd.FrameLoadEnd += WebBrowserFrameLoadEnded;

int tryCount = 0;

do
{
    Thread.Sleep(3000);

    RtnHtml = globalRtnVal;

    if (String.IsNullOrEmpty(RtnHtml))
        tryCount++;

    if (tryCount == 10 && String.IsNullOrEmpty(RtnHtml))
    {
        /* some codes */
        return null;
    }
}
while (String.IsNullOrEmpty(RtnHtml));

/* some codes */
YSFKBDY
  • 735
  • 1
  • 12
  • 38
  • It's unclear what your trying to achieve. See https://github.com/cefsharp/CefSharp/blob/master/CefSharp.OffScreen.Example/Program.cs for an example that uses async/await. Msdn has some quite detailed articles on async programming I'd suggest you read some if you haven't already. – amaitland Feb 22 '18 at 12:03
  • @amaitland Thanks for your reply. I am trying to get some page's html codes after the EvaluateScriptAsync completed. But my code - above - is not waiting and returns html codes immediately. That's my problem. Hope I could explain. – YSFKBDY Feb 22 '18 at 13:23
  • You can use a TaskCompletionSource and await the LoadingStateChanged event, then await the JavaScript, sleep for a little bit then get the source. The link I provided has some await examples you can adapt. Do some more research on await async programming – amaitland Feb 23 '18 at 01:23

0 Answers0