Jim*_*man 8 c# windows-runtime winjs win-universal-app uwp
我正在尝试使用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
Run Code Online (Sandbox Code Playgroud)
如果我使用Creator的更新(15063)作为最小值运行此代码,那么代码运行正常.
我创建了一个包含示例解决方案的Github仓库,该解决方案在本地运行时为我生成错误.
这是main.js的样子.尝试运行getExample函数时发生错误:
// Your code here!
var test = new RuntimeComponent1.Class1;
test.getExample().then(result => {
console.log(result);
});
Run Code Online (Sandbox Code Playgroud)
这就是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";
}
}
}
Run Code Online (Sandbox Code Playgroud)
我想不出比这更简单的测试用例 - 我没有安装NuGet包或类似的东西.我不知道是什么原因引起的.其他人有想法吗?
即使作为一个简化的示例,该函数实际上并没有什么异步之处
private async Task<string> getExample()
{
return "It's working";
}
Run Code Online (Sandbox Code Playgroud)
另外,如果所述函数已经返回 aTask则无需将其包装在Task.Run这里
return AsyncInfo.Run(token => Task.Run(getExample));
Run Code Online (Sandbox Code Playgroud)
重构代码以遵循建议的语法
public sealed class Class1 {
public IAsyncOperation<string> GetExampleAsync() {
return AsyncInfo.Run(token => getExampleCore());
}
private Task<string> getExampleCore() {
return Task.FromResult("It's working");
}
}
Run Code Online (Sandbox Code Playgroud)
由于没有什么可等待的,因此使用从私有函数Task.FromResult返回。Task<string>getExampleCore()
另请注意,由于原始函数返回未启动的任务,因此这会导致MethodInvalidOperationException抛出异常AsyncInfo.Run<TResult>(Func<CancellationToken, Task<TResult>>)
AsAsyncOperation<TResult>考虑到被调用函数的简单定义,您还可以考虑利用扩展方法。
public IAsyncOperation<string> GetExampleAsync() {
return getExampleCore().AsAsyncOperation();
}
Run Code Online (Sandbox Code Playgroud)
并在 JavaScript 中调用
var test = new RuntimeComponent1.Class1;
var result = test.getExampleAsync().then(
function(stringResult) {
console.log(stringResult);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
345 次 |
| 最近记录: |