简体   繁体   中英

Using await in async methods to prevent next line of code from running

I'm new to using async methods, so I think I'm misunderstanding something. I have a WinForms app with a button, and when the button is clicked, an async method gets called. This must be async, as I need to make javascript calls to a Chromium Web Browser control (using CefSharp). I need to ensure that this javascript has finished running and that the browser has updated before continuing with the next part of the method.

I'm basically trying to capture the entire web page into a single image. My approach was to use javascript to update the scroll position on the page, then take screenshots in each position using Graphics.CopyFromScreen. This mostly works, however occasionally the resulting image will have the wrong 'chunk' of webpage (eg, the first bitmap is repeated twice). Here is my code:

// Calculate screen sizes, screenshot spacing etc.

for (int i = 0; i < screenshotCount; i++)
{
    int scrollSize = i == 0 ? -PageHeight : (int)browserControlHeight;
    string script = "(function() { window.scrollBy(0, " + scrollSize.ToString() + ") })();";

    await browser.EvaluateScriptAsync(script);

    // Take screenshot, add to list of bitmaps
}

// Combine resulting list of bitmaps

If I add the following

await Task.Delay(1000);

after the EvaluateScriptAsync() call, the final image comes out correct every time. I'm working on the assumption that the javascript is being called but doesn't complete before the screenshot begins. If this is the case, even adding a delay may not work (what if the javascript takes longer than a second to run?).

Am I misunderstanding the way that async/await works?

No, the issue is not with await , the issue is that the Task returned from EvaluateScriptAsync is being marked as completed before you're ready to continue. It's going to be marked as completed as soon as the javascript to inform the browser that it should scroll has executed, rather than being marked as completed after the browser has finished re-rendering the screen after being sent the scroll command.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM