问题
Currently I'm developing an universal app using c#.
In app I used sqlite as database and as you may now It has async methods.
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.
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.
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?
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
回答1:
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.
来源:https://stackoverflow.com/questions/29216679/calling-async-method-in-class-constructor-in-c-sharp