使异步事件在JavaScript中同步 [英] Make async event synchronous in JavaScript

查看:38
本文介绍了使异步事件在JavaScript中同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用WPF 3.5SP1 WebBrowser控件来显示包含一些javascript函数的页面.然后,我的程序需要调用一个JavaScript函数,该函数将进行异步调用.我需要一种方法来将异步调用的结果返回给C#,以便我可以处理结果.

I'm using the WPF 3.5SP1 WebBrowser control to display a page containing some javascript functions. My program then needs to invoke a javascript function which will make an asynchronous call. I need a way to get the result of that asynchronous call back to C# so I can process the result.

有没有办法让第一个javascript函数进入休眠状态,直到发生某些事情(不锁定浏览器)?

Is there a way I can make the first javascript function sleep until something happens (with out locking up the browser)?

编辑:我已经在使用回叫功能-第二个功能实际上称为"some-async-function-complete".异步事件结束时将调用它.现在,我需要一种将结果导入C#的方法.

edit: I am already using a call back - the 2nd function is actually called "some-async-function-complete". It gets called when the async event finishes. Now I need a way to get the result into C#.

为进一步说明:C#

var result = WebBrowser.InvokeScript("myscript")

JavaScript

JavaScript

var result;

function myscript()
{
some-async-function();
/* what goes here? */
/* wait until result != null */
return result;
}

function some-async-function-complete(retval)
{
result = retval;
}

推荐答案

有没有一种方法可以使我成为第一个javascript函数休眠直到发生了一些事情(没有锁定浏览器)?

Is there a way I can make the first javascript function sleep until something happens (with out locking up the browser)?

是的-您可以按预期使用异步函数:将其传递给回调函数,然后让它完成其任务.您应该能够将C#中的回调传递到JS函数中,然后可以将其直接传递给异步函数,或者如果需要后处理,则可以将其包装在另一个函数中.

Yes - you can use the asynchronous function as it was intended to be used: pass it a callback, and let it do its thing. You should be able to pass a callback from C# into your JS function, which can then either pass it to your asynchronous function directly, or wrap it in another function if post-processing is required.

实现回调的示例-可以与WinForms WebBrowser控件一起使用,我尚未使用WPF对其进行过测试,但它们应该大致相同:

An example of the implementation of a callback - this works with the WinForms WebBrowser control, i haven't tested it with WPF but they should be pretty much the same:

[System.Runtime.InteropServices.ComVisibleAttribute(true)]
public class Callback
{
   // allows an instance of Callback to look like a function to the script
   // (allows callback() rather than forcing the script to do callback.callMe)
   [System.Runtime.InteropServices.DispId(0)]
   public void callMe(string url)
   {
      // whatever you want to happen once the async process is complete
   }
}

...

Callback cb = new Callback();
WebBrowser.InvokeScript("myscript", new object[] { cb })

...

function myscript(callback)
{
   some_async_function(function()
   {
      // script-specific completion code
      if ( callback )
         callback();
   });
}

这篇关于使异步事件在JavaScript中同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆