在使用JavaScript UWP应用程序时,使用Windows Runtime组件会出现“未知运行时错误”

8
我正在尝试使用Windows Runtime组件在我的Javascript UWP应用程序和我编写的C#逻辑之间提供互操作性。如果我将最小版本设置为Fall Creator's Update(构建16299,需要使用.NET Standard 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 的更新版(15063)作为最低要求来运行,则该代码可以正常运行。
我创建了一个 Github 仓库,其中包含一个样本解决方案,当我在本地运行时会生成错误。
以下是 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包或其他任何东西。我不知道可能是什么原因导致这种情况。还有其他人有什么想法吗?

2个回答

1

其实这个函数并没有任何异步操作,即使作为一个简化的例子。

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<TResult>(Func<CancellationToken, Task<TResult>>)方法引发InvalidOperationException异常。

考虑利用AsAsyncOperation<TResult>扩展方法,鉴于所调用函数的简单定义。

public IAsyncOperation<string> GetExampleAsync() {
    return getExampleCore().AsAsyncOperation();
}

在JavaScript中调用

var test = new RuntimeComponent1.Class1;

var result = test.getExampleAsync().then(
    function(stringResult) {
        console.log(stringResult);
    });

2
虽然这是重构我提供的示例代码的好建议,但据我所知,它实际上并没有解决我需要答案的“未知运行时错误”。即使应用了这些修复程序,异常仍会被抛出。 - Courtney

0

这不是正确的异步方法:

private async Task<string> getExample()
{
    return "It's working";
}

这是因为它应该返回 Task<string>,而不仅仅是 string
所以,你应该将其更改为:
private async Task<string> getExample()
{
    return Task.FromResult("It's working");
}

2
虽然这是对我提供的示例代码进行重构的好建议,但据我所知,它实际上并没有解决我需要答案的“未知运行时错误”。即使应用了这个修复方法,异常仍然会被抛出。 - Courtney

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接