使用Windows运行时组件与Javascript UWP应用程序时出现“未知运行时错误”

问题描述 投票:8回答:2

我正在尝试使用Windows运行时组件来提供我的Javascript UWP应用程序和我编写的C#逻辑之间的互操作性。如果我将最低版本设置为Fall Creator的更新(构建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 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包或类似的东西。我不知道是什么原因引起的。其他人有想法吗?

c# uwp windows-runtime win-universal-app winjs
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从私人Task<string>函数返回getExampleCore()

请注意,因为原始函数返回未启动的任务,这导致InvalidOperationException抛出AsyncInfo.Run<TResult>(Func<CancellationToken, Task<TResult>>) Method

考虑到被调用函数的简单定义,您还可以考虑利用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);
    });

0
投票

这不是正确的异步方法:

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

原因是它应该返回Task<string>,而不仅仅是string

所以,你应该把它改成:

private async Task<string> getExample()
{
    return Task.FromResult("It's working");
}
© www.soinside.com 2019 - 2024. All rights reserved.