小编XJo*_*neX的帖子

这是重新配置构造函数以使用异步和等待的正确方法吗?

我读过几篇文章,但我很难理解这一点。我试图在加载一些数据时保持 MAUI 应用程序的 UI 更新。

我想完成这个:

async public DataService()
{
    //initialize stuff here
    await this.GetPayees();
    await this.GetCategories();
    return;
}
Run Code Online (Sandbox Code Playgroud)

我读到你不能有异步构造函数,所以我不得不重做如何初始化我的类。

public DataService()
{
    //Take this out here
    //this.GetPayees();
    //this.GetCategories();
    return;
}

async public static Task<DataService> BuildDataServiceAsync()
{
    //await them here
    var dataService = new DataService();
    await dataService.GetPayees();
    await dataService.GetCategories();
    return dataService;
}
Run Code Online (Sandbox Code Playgroud)

这对我的代码产生了连锁效应。我必须将返回类型更改为任务,并使其他方法异步

async public Task<List<Payee>> GetPayees()
{
    //Load arbitrary data, 
    if(Payees.Count != 0) return Payees;
    Payees.Add(new Payee { Id = 0, Name = "Food Lion", DefaultCategoryId = 0, DefaultIsCredit …
Run Code Online (Sandbox Code Playgroud)

c# asynchronous async-await

0
推荐指数
1
解决办法
55
查看次数

标签 统计

async-await ×1

asynchronous ×1

c# ×1