Reputation: 1862
I have an UWP app and I added OnBackRequested(object sender, BackRequestedEventArgs e)
, in a couple places. However I found one interesting problem. That is when I add async
to some of the OnBackRequested
event, I actually will get backbutton remember how many times it has been tapped. That is to say, the first time I click it, async OnBackRequested
will get triggered once, and the second I click it, async OnBackRequested
will get triggered twice and so on so forth. I'm wondering if this is an OS bug or anything else. And how can I resolve this. Thank you!
Upvotes: 1
Views: 680
Reputation: 45173
To explain why BackRequested
is happening twice when you make your handler async: It's because you are performing an async operation before setting Handled = true
. When you declare a method as async
, then when it performs an await
, the method queues up a task and returns. When the thing being awaited completes, the queued-up task runs, and that task resumes execution of the method (until the next await
).
The BackRequested
event handler doesn't know that you queued up a task. It sees that the handler returned, and it checks whether you set Handled
, and since you haven't set Handled = true
(yet), it concludes that the handler didn't want to handle the BackRequested
event, so it calls the next handler.
So what you're seeing is the combination of two problems.
await
before setting Handled = true
.You still have a problem: Since your handler isn't setting Handled = true
before performing its await
, the BackRequested
event concludes that you didn't handle the event, and it will try to handle the event for you (probably by navigating to the previous app).
TL;DR: If you are going to do async stuff in the BackRequested
event, make sure to set Handled = true
before your first async operation.
Upvotes: 2
Reputation: 1942
I think that you forget to remove the handler of OnBackRequested.
When navigating to new page, I think you did:
OnBackRequested += .....
But when you navigate from it, you forget to call OnBackRequested -= ......
Upvotes: 1