.Result()使方法挂起时,如何在构造函数中使用异步方法?

iSp*_*n17 0 c# sqlite mvvm xamarin.forms sqlite-net-pcl

当Xamarin.Forms项目中出现页面时,我有一个AppearingCommand调用,该页面最终执行以下sqlite-net-pcl行:(我已经有一种应对加载时间的机制)

AppearingCommand = new Command( async() => {
    //...
    var data = await db.Table<PlantCategory>().ToListAsync();
    //...
}
Run Code Online (Sandbox Code Playgroud)

我想将此方法移到构造函数中,但我不能这样做,因为如果同步执行它会挂起:

ctor() {
    //...
    var data = db.Table<PlantCategory>().ToListAsync().Result;
    //...
}
Run Code Online (Sandbox Code Playgroud)

该行永远不会返回(我猜是由于死锁或其他原因)。如果要在构造函数中执行此行,我还有什么其他选择?

Mar*_*ell 5

简单。别。

相反,请添加类似的后构建方法,async ValueTask InitAsync()然后使用进行调用await

可以隐藏这个背后static ValueTask<Whatever> CreateAsync(...)方法调用来代替 new Whatever(...),即

class Whatever {
    private Whatever(...) { ... } // basic ctor
    private async ValueTask InitAsync(...) { ... } // async part of ctor

    public static async ValueTask<Whatever> CreateAsync(...) {
        var obj = new Whatever(...);
        await obj.InitAsync(...);
        return obj;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @ iSpain17`ValueTask [&lt;T&gt;]`降至.NET Standard 1.0和.NET 4.5 https://www.nuget.org/packages/System.Threading.Tasks.Extensions/4.5.3 (2认同)