【问题标题】:Xamarin/C#/SQlLite - Why is my SUM query returning 'System.Threading.Task'?Xamarin/C#/SQlite - 为什么我的 SUM 查询返回“System.Threading.Task”?
【发布时间】:2021-12-02 02:42:16
【问题描述】:

问题:我有一个页面将显示我对我的 SQLite DB 进行的各种 SQL 查询的结果。第一个应该取一列的总和并返回它。我使用了各种资源,详细说明了如何进行 SQL 查询并将它们作为可用变量返回,但我显然没有成功。这当前将“System.Threading.Task”作为字符串返回。希望了解我在这里出错的地方。

我的数据库方法来获取 DAYS 列的总和:

public Task<int> getLeaveDaysSum()
    {
        return _database.ExecuteScalarAsync<int>("SELECT SUM(DAYS) from [LeaveEntry]");
    }

我的 OnAppearing 方法将更新页面标签以显示上述方法的结果:

protected override void OnAppearing()
    {
        base.OnAppearing();

        LeaveTakenDays.Text = App.Database.getLeaveDaysSum().ToString();
    }

与往常一样,如果我可以提供更多详细信息,请告诉我。感谢所有帮助。

【问题讨论】:

    标签: c# sqlite xaml xamarin


    【解决方案1】:

    您需要使用await 关键字,因为这是一个异步方法(并且还使用后缀异步更改方法名称)

    async 修饰符指定此方法是异步的,当调用异步方法时,会返回一个任务。当await 运算符应用于任务时,当前方法会立即退出。任务完成后,以相同的方法继续执行,这就是您的代码中缺少的内容。

    public async Task<int> getLeaveDaysSumAsync()
    {
        var count = await _database.ExecuteScalarAsync<int>("SELECT SUM(DAYS) from 
    [LeaveEntry]");
    
         return count;
    }
    
    protected async override void OnAppearing()
    {
        base.OnAppearing();
    
        var count = await App.Database.getLeaveDaysSumAsync();
        LeaveTakenDays.Text = count.ToString();
    }
    

    更多关于 async/await 的信息可以在这里找到:https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/asynchronous-programming

    【讨论】:

    • 谢谢,就是这样!我在项目的其他地方使用过异步方法,我只是认为我默认使用标准方法,我认为不需要异步。吸取教训!
    • 不客气,我的朋友
    猜你喜欢
    • 2016-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多