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

淺唱寂寞╮ 提交于 2020-12-26 03:59:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!