gpt4 book ai didi

javascript - 在 CefSharp 中从 JS 调用异步方法

转载 作者:行者123 更新时间:2023-11-29 17:54:42 24 4
gpt4 key购买 nike

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

我的想法是:我使用以下签名调用一个方法:

public async Task<int> Calculate(){

当它完成时,它的结果将通过 JS 端的 promise 返回。目前,它不起作用。完成后没有回调,然后我无法再次调用它。

谢谢

最佳答案

我遇到了同样的问题。

一个丑陋的解决方法似乎是将你的方法改造成 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());
}
}

绑定(bind)对象的方法将类似于:

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")

关于javascript - 在 CefSharp 中从 JS 调用异步方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40384238/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com