在CefSharp中调用JS中的async方法

本文关键字:中的 async 方法 JS 调用 CefSharp | 更新日期: 2023-09-27 18:16:03

如何在CefSharp中调用。net异步方法?我想调用一个等待控制台应用程序调用的方法。

我的想法如下:我调用了一个签名如下的方法:

public async Task<int> Calculate(){

,当它完成时,它的结果将通过JS端的承诺返回。目前,它不起作用。当它完成时,没有回调,然后我就不能再调用它了。

谢谢

在CefSharp中调用JS中的async方法

我遇到了同样的问题。

一个丑陋的解决方案似乎是将您的方法修改为async void并接受两个IJavascriptCallback参数(resolvereject)。

例如:

public class MyCalculator
{
    public async void CalcAsync(
        string name,
        IJavascriptCallback resolve,
        IJavascriptCallback reject)
    {
        try
        {
            if (resolve.IsDisposed)
                return;
            int i = /* compute i */;
            if (!resolve.IsDisposed)
               await resolve.ExecuteAsync(i);
        }
        catch (Exception e)
        {
            if (!reject.IsDisposed)
                await reject.ExecuteAsync(e.ToString());
        }
    }
}
注册:

browser.RegisterAsyncJsObject("myCalculator", new MyCalculator());

然后在JavaScript中:

function doThingAsync(name) {
    return new Promise(function (resolve, reject) {
        window.myCalculator.calcAsync(name, resolve, reject);
    });
}
var result = await doThingAsync("foo")

你可以像这样把模式拉出来:

private static async Task Promisify(IJavascriptCallback resolve, IJavascriptCallback reject, Func<Task> action)
{
    try
    {
        if (!resolve.IsDisposed)
            await action();
        if (!resolve.IsDisposed)
            await resolve.ExecuteAsync();
    }
    catch (Exception e)
    {
        if (!reject.IsDisposed)
            await reject.ExecuteAsync(e.ToString());
    }
}
private static async Task Promisify<T>(IJavascriptCallback resolve, IJavascriptCallback reject, Func<Task<T>> action)
{
    try
    {
        var result = default(T);
        if (!resolve.IsDisposed)
            result = await action();
        if (!resolve.IsDisposed)
            await resolve.ExecuteAsync(result);
    }
    catch (Exception e)
    {
        if (!reject.IsDisposed)
            await reject.ExecuteAsync(e.ToString());
    }
}

绑定对象的方法类似于:

public class MyCalculator
{
    public async void CalcAsync(
        string name,
        IJavascriptCallback resolve,
        IJavascriptCallback reject)
    {
        Promisify(resolve, reject, () => /* compute i */);
    }
}

我想使用的(假设的)API类似于:
public class MyCalculator
{
    public async Task<int> CalcAsync(string name) => /* compute i */;
}

:

var result = await window.myCalculator.calcAsync("foo")