Gk_999
Gk_999

Reputation: 518

Update SQLite db & use updated records in same async fuction

I'm using this method to update a tuple of a particular table

public async void Update(MyTable entity)
{
    SQLiteAsyncConnection conn = new SQLiteAsyncConnection(path);
    await conn.UpdateAsync(entity); 
}

Reference: http://msdn.microsoft.com/en-us/library/windows/apps/dn263243.aspx

Now in main, i'm trying to update a record in MyTable & I'm binding MyTable records to a ViewModel which is bound to the view.

private async void button_Tapped(object sender, TappedRoutedEventArgs e)
{
    MyTableRepository.Update(scheduleRecord);

    this.DefaultViewModel["MyViewModel"] =await ViewModelClass.GetMyTableDataAsync();
}

The problem here is that the view is not getting updated. After I stop the application & check db values, the db seems to be updated & after that if i run the app again, the required updated view is displayed.

I'm new to async-await. So my feeling is that maybe ViewModel is updated even before

MyTableRepository.Update(scheduleRecord);

is executed. I actually dont know the exact cause. Please Help.

Upvotes: 1

Views: 2257

Answers (1)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149538

Your Update method is running in a "fire and forget" fasion. When you await GetMyTableDataAsync(), the data may not yet be updated in your database.

What you need to do is change Update from async void to async Task:

public async Task UpdateAsync(MyTable entity)

and await on it:

await UpdateAsync(entity);

Your full code would look like this:

private async void button_Tapped(object sender, TappedRoutedEventArgs e)
{
    await MyTableRepository.UpdateAsync(scheduleRecord);

    this.DefaultViewModel["MyViewModel"] = await ViewModelClass.GetMyTableDataAsync();
}

As a side note:

  1. If you're not doing anything other then awaiting inside UpdateAsync, you can simply return the executing Task and await it higher up the call chain:

    public Task UpdateAsync(MyTable entity)
    {
       SQLiteAsyncConnection conn = new SQLiteAsyncConnection(path);
       return conn.UpdateAsync(entity); 
    }
    
  2. Make sure you're properly disposing your DB connections.

Upvotes: 2

Related Questions