插件-正在使用中的任务类.Net 4.0解决方法
本文关键字:Net 方法 解决 任务 插件 | 更新日期: 2023-09-27 17:57:49
我正在为我的unity游戏编写一个应用内购买插件,该插件需要使用。Net 3.5框架。
因此,从文件参考:unity WP8插件文档
它指出:"…实现与真实DLL中相同的非私有方法/字段/属性"
因此,我尝试将其应用于以下方法,该方法需要在等待方法时使用Task类。
这就是实际工作的方法。
public async Task<bool> PurchaseUpgrade(string ID)
{
var listings = await CurrentApp.LoadListingInformationAsync();
//The rest of the method-body is irrelevant...
So this won't compile as-is.
}
所以,是的,我需要在编辑器"使用"的dll中写一个方法,只需要一个匹配的签名,唉,由于Task类的原因,我做不到。
public async Task<bool> PurchaseUpgrade(string ID)
{
//This could literally be empty if the method was void, but need it to return
Task<bool>, and can't work out how
return true;
}
有谁能深入了解我如何做到这一点?
提前感谢
您应该能够使用Task.FromResult<T>()
方法。
return Task.FromResult(true);
或者如果你不能使用。NET 4.5,试试这个:
return Task.Factory.Start(() => true);
我发现这个问题的答案是封装。异步方法需要是私有的,并由公共方法调用它们。
在目标dll中。Net 4.0或更高版本您有这样的异步方法:
private async void Foo()
{
await LongRunningMethod();
}
public void Bar()
{
//Call the async method
Foo();
}
现在要在Unity中使用上面的dll,你必须创建一个目标dll。Net3.5,并让它包括任何方法,以及您希望在统一脚本中使用的匹配签名。
所以在。Net 3.5 dll你只需要:
public void Bar()
{
//This can literally be empty if you want
}
就这样…几乎是
两个dll的程序集名称和默认命名空间属性必须匹配。
。Net 3.5 dll需要放在文件夹中
/Assets/Plugins
还有。Net 4.0 dll需要放在文件夹中
/Assets/Plugins/WP8
这样,在统一编辑器中工作时就不会出现任何编译错误,方法从调用。将调用Net 3.5 dll。然而,当你在WP8设备上运行时。Net4.0将被称为真正的"魔术"。
希望这能帮助到任何人。
注意:正如下面的注释中所述,值得一提的是,您将无法捕获Async void方法引发的异常。
您可能认为这会捕获异步void方法引发的异常:
public void CallAsyncMethod()
{
try
{
Foo(); //The async void mentioned above
}
catch(Exception)
{
//But it doesn't
}
}
为了能够使用异步void方法编写"安全"代码,您需要在异步void方法中添加异常处理,如下所示:
private async void Foo()
{
try
{
await LongRunningMethod();
}
catch(Exception)
{
//This is now safe, the exception will be caught, although admittedly
// ugly code, better to have it in the called IMO.
}
}