Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Async method in class constructor in C# [duplicate]

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

like image 979
RaminMT Avatar asked Oct 26 '25 18:10

RaminMT


1 Answers

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.

like image 197
Steven A. Lowe Avatar answered Oct 29 '25 08:10

Steven A. Lowe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!