在C#中的类构造函数中调用Async方法 [英] Calling Async method in class constructor in C#
问题描述
目前,我正在使用c#开发通用应用程序.
Currently I'm developing an universal app using c#.
在应用程序中,我将sqlite用作数据库,并且您现在可能拥有异步方法.
In app I used sqlite as database and as you may now It has async methods.
我有一个带有一些null属性的类,我将使用从db中获取的数据来填充它们,但是应该完全在类构造函数中完成.
I have a class with some null property that I'll fill them using data I fetch from db, but It should be done exactly in class constructor.
问题是不允许使用异步方法,因此我尝试创建一个新的异步方法,并使用sqlite方法并在其中填充属性以在构造函数中同步调用它,但可以预期它不能很好地工作.
The problem is that using async methods is not allowed, So I tried creating a new async method and using sqlite methods and filling properties in it to call it synchronously in constructor, but as may expecting It doesn't work well.
如何在类构造函数中使用异步方法来从db获取数据并在类构造函数方法中填充类属性?
How can I use async method in class constructor in a way to get data from db and fill class properties right in class constructor method?
更新:请注意,我并不是在问这是否可以完成,我想使用在类构建时来自db的数据来初始化我的类vars
Update: Notice that I'm not asking about could it be done or no, I want to init my class vars with data coming from db when the class constructed
推荐答案
不要这样做
构造函数应该简单地是:构造函数.将复杂的初始化移动到一个初始化方法.
Don't do that
Constructors should be simply that: constructors. Move complex initializations to an initialize method.
构造函数正常失败的能力有限,因此不要对它们进行任何复杂,长时间运行或脆弱的操作.
Constructors have a limited ability to fail gracefully, so don't do anything complicated, long-running, or fragile in them.
这篇关于在C#中的类构造函数中调用Async方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!