Home > Blockchain >  Xamarin/C#/SQlLite - Why is my SUM query returning 'System.Threading.Task'?
Xamarin/C#/SQlLite - Why is my SUM query returning 'System.Threading.Task'?

Time:10-14

Problem: I have a page which is going to display the results of a variety of SQL queries I'm making against my SQLite DB. This first one is supposed to take the sum of a column and return it. I've used a variety of resources that detail how you make SQL queries and return them as useable variables but I've obviously not been successful. This is currently returning 'System.Threading.Task' as a string. Would love some insight as to where I've gone wrong here.

My DB method to get the sum of the DAYS column:

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

My OnAppearing method which will update the page label to display the result of the above method:

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

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

As always, if I can provide further details, please let me know. All help appreciated.

CodePudding user response:

You need to use the await keyword since this is an async method (and also change the method name with postfix Async)

The async modifier specifies that this method is asynchronous and when calling an async method, a task is returned. When the await operator is applied to a task, the current method exits immediately. When the task finishes, execution resumes in the same method and this is what was missing in your code.

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();
}

More about async/await can be found here: https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/asynchronous-programming

  • Related