在 C# 中的类构造函数中调用异步方法 [英] Calling Async method in class constructor in C#

查看:43
本文介绍了在 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.

我有一个带有一些空属性的类,我将使用从数据库中获取的数据填充它们,但它应该完全在类构造函数中完成.

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.

如何在类构造函数中使用异步方法以从数据库获取数据并在类构造函数方法中正确填充类属性?

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 的数据初始化我的类变量

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# 中的类构造函数中调用异步方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆