Reputation: 24572
My code looks like this:
async public Task Btn(int pts)
{
switch (Settings.mode)
{
case MO.Assign:
case MO.Learn:
break;
case MO.Quiz:
await Task.Run(() => App.DB.IncrementPoints(phrase, 1));
await Task.Delay(250);
break;
case MO.Practice:
Device.BeginInvokeOnMainThread(() =>
{
vm.Points = new String('☆', phrase.Points + pts);
});
await Task.Run(() =>
{
App.DB.IncrementPoints(phrase, pts);
App.DB.IncrementHistory(HIST.Views);
});
await Task.Delay(250);
break;
}
App.selectedPhrases = null;
timer2Seconds = 2;
}
public void IncrementPoints(Phrase phrase, int pts)
{
lock (l)
{
db2.Execute("UPDATE phrase SET Points = Points + " + pts +
" WHERE PhraseId = '" + phrase.PhraseId + "'");
}
}
I am a bit confused with Task.Run and await. First of all I want this to update the screen:
vm.Points = new String('☆', phrase.Points + pts);
Then I want the database to be updated and then there to be a delay of 250ms.
But is it okay that my method IncrementPoints is not an async method?
Upvotes: 0
Views: 80
Reputation: 271175
I am not exactly sure what you want to do, but to answer your question:
But is it okay that my method IncrementPoints is not an async method?
Yes, it's ok, and that is also exactly one of the purposes of Task.Run
. You can use Task.Run
to turn synchronous operations to awaitable async operations. So you are supposed to put non-async methods in the lambda. If IncrementPoints
were async, you wouldn't need Task.Run
, because you can just do:
await IncrementPoints(...);
Your code should just be something like this:
vm.Points = new String('☆', phrase.Points + pts);
await Task.Run(() =>
{
App.DB.IncrementPoints(phrase, pts);
App.DB.IncrementHistory(HIST.Views);
});
await Task.Delay(250);
Upvotes: 3