简体   繁体   English

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

[英]How to use asynchronous method in constructor when .Result() makes the method hang?

I have an AppearingCommand called when a Page appears in my Xamarin.Forms project, that eventually executes the following sqlite-net-pcl line: (I already have a mechanism coping with loading time) 当Xamarin.Forms项目中出现页面时,我有一个AppearingCommand调用,该页面最终执行以下sqlite-net-pcl行:(我已经有了一种处理加载时间的机制)

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

I want to move this method to the constructor, but I cannot do it, as it hangs if it is executed synchronously: 我想将此方法移到构造函数中,但我不能这样做,因为如果同步执行它会挂起:

ctor() {
    //...
    var data = db.Table<PlantCategory>().ToListAsync().Result;
    //...
}

The line never returns (I am guessing because of a deadlock or something). 该行永远不会返回(我猜是由于死锁或其他原因)。 What are other options that I have if I want to execute this line inside the constructor? 如果要在构造函数中执行此行,我还有什么其他选择?

Simple. 简单。 Don't. 别。

Instead, add a post-construction method like async ValueTask InitAsync() and call that with await . 相反,请添加诸如async ValueTask InitAsync()类的后构造方法,并使用await调用。

You could hide this behind a static ValueTask<Whatever> CreateAsync(...) method that you call instead of new Whatever(...) , ie 您可以将其隐藏在static ValueTask<Whatever> CreateAsync(...)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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM