我正在尝试使用Windows Runtime组件来提供我的Javascript UWP应用程序和我编写的C#逻辑之间的互操作性。如果我将最低版本设置为Fall Creator's Update (build 16299,需要使用.NET标准2.0库),则在尝试调用简单方法时会出现以下错误:
Unhandled exception at line 3, column 1 in ms-appx://ed2ecf36-be42-4c35-af69-93ec1f21c283/js/main.js
0x80131040 - JavaScript runtime error: Unknown runtime error如果我使用Creator's Update (15063)作为最低版本运行这段代码,那么代码运行得很好。
我已经创建了一个包含示例解决方案的Github repo,该解决方案在本地运行时会为我生成错误。
这是main.js的样子。尝试运行getExample函数时出现错误:
// Your code here!
var test = new RuntimeComponent1.Class1;
test.getExample().then(result => {
console.log(result);
});这是Class1.cs的样子:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text;
using System.Threading.Tasks;
using Windows.Foundation;
namespace RuntimeComponent1
{
public sealed class Class1
{
public IAsyncOperation<string> GetExample()
{
return AsyncInfo.Run(token => Task.Run(getExample));
}
private async Task<string> getExample()
{
return "It's working";
}
}
}我想不出比这更简单的测试用例了--我没有安装NuGet包或类似的东西。我不知道这可能是什么原因。还有人有主意吗?
发布于 2018-07-07 20:57:27
这个函数实际上并不是异步的,即使是作为一个简化的例子。
private async Task<string> getExample()
{
return "It's working";
}另外,如果上述函数已经返回了Task,则不需要在这里将其包装在Task.Run中
return AsyncInfo.Run(token => Task.Run(getExample));重构代码以遵循建议的语法
public sealed class Class1 {
public IAsyncOperation<string> GetExampleAsync() {
return AsyncInfo.Run(token => getExampleCore());
}
private Task<string> getExampleCore() {
return Task.FromResult("It's working");
}
}因为没有什么需要等待的,所以使用Task.FromResult从私有的getExampleCore()函数返回Task<string>。
还要注意,因为原始函数返回的是未启动的任务,所以这会导致AsyncInfo.Run(Func>) Method抛出InvalidOperationException
您还可以考虑利用AsAsyncOperation扩展方法,给出被调用函数的简单定义。
public IAsyncOperation<string> GetExampleAsync() {
return getExampleCore().AsAsyncOperation();
}并在JavaScript中调用
var test = new RuntimeComponent1.Class1;
var result = test.getExampleAsync().then(
function(stringResult) {
console.log(stringResult);
});发布于 2018-07-09 01:48:00
这不是正确的异步方法:
private async Task<string> getExample()
{
return "It's working";
}这样做的原因是它应该返回Task<string>,而不仅仅是string。
因此,您应该将其更改为:
private async Task<string> getExample()
{
return Task.FromResult("It's working");
}https://stackoverflow.com/questions/51094389
复制相似问题