简体   繁体   English

在异步方法中使用await防止运行下一行代码

[英]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. 我有一个带有按钮的WinForms应用程序,单击该按钮时,将调用一个异步方法。 This must be async, as I need to make javascript calls to a Chromium Web Browser control (using CefSharp). 这必须是异步的,因为我需要对Chromium Web浏览器控件进行JavaScript调用(使用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. 在继续进行该方法的下一部分之前,我需要确保此javascript已经运行完毕并且浏览器已更新。

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. 我的方法是使用javascript更新页面上的滚动位置,然后使用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. 在EvaluateScriptAsync()调用之后,最终的图像每次都会正确显示。 I'm working on the assumption that the javascript is being called but doesn't complete before the screenshot begins. 我正在假设正在调用javascript,但在截屏开始之前未完成javascript。 If this is the case, even adding a delay may not work (what if the javascript takes longer than a second to run?). 在这种情况下,即使添加延迟也可能不起作用(如果JavaScript花费的时间超过一秒钟怎么办?)。

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. 不,问题不在await ,问题在于从EvaluateScriptAsync返回的Task在准备好继续之前被标记为已完成。 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. 一旦通知浏览器它应该执行滚动的javascript,它将被标记为完成,而不是在发送了scroll命令后,浏览器完成了对屏幕的重新渲染之后,将其标记为完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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