Is it true that a delay should be added for any asynchronous operation?

According to Likness (p. 164, “Creating Windows 8 Applications Using C # and XAML”), “When performing asynchronous tasks, you should ask for a delay.”

So, if I don't get it out of context, this code:

private async Task<System.Collections.Generic.KeyValuePair<string, string>> SelectAContactForASlot() { KeyValuePair<string, string> kvp; var contactPicker = new Windows.ApplicationModel.Contacts.ContactPicker(); contactPicker.CommitButtonText = "Select"; var contact = await contactPicker.PickSingleContactAsync(); if (contact != null) { kvp = new KeyValuePair<string, string>(contact.Name, contact.Emails[0].ToString()); return kvp; } return kvp = new KeyValuePair<string, string>("No Name found", "No email found"); } 

... should be this:

 private async Task<System.Collections.Generic.KeyValuePair<string, string>> SelectAContactForASlot() { var deferral = e.SuspendingOperation.GetDeferral(); KeyValuePair<string, string> kvp; var contactPicker = new Windows.ApplicationModel.Contacts.ContactPicker(); contactPicker.CommitButtonText = "Select"; var contact = await contactPicker.PickSingleContactAsync(); if (contact != null) { kvp = new KeyValuePair<string, string>(contact.Name, contact.Emails[0].ToString()); return kvp; } return kvp = new KeyValuePair<string, string>("No Name found", "No email found"); deferral.Complete(); } 

Right?

+4
source share
1 answer

Remember that the async method returns when it gets into await and must (asynchronously) wait.

You need a delay when you await perform an operation from the async void method, which must complete before it returns. Such an “event” is truly a team. For example, a "moved mouse" is just an event - the system does not care if you are handling the event. But "suspend" is a command - the system assumes that when you return from the team, you will be ready to pause. In this case, grace periods are needed to tell the system that even if you return, you are not finished yet.

Similarly, you will need a delay if you have a background task with the implementation of async Run . Because when Run returns, your background task is considered complete, and you need a way to say what you haven't done yet.

You can find out if the event handler supports the presence of the GetDeferral method. For example, Suspending supports deferral because SuspendingEventArgs has the SuspendingOperation property, which has the GetDeferral method. In the background task script (i.e., you have async void Run ), you can call GetDeferral on the IBackgroundTaskInstance passed to Run .

Your SelectAContactForASlot example returns a Task , so it doesn't need a delay.

+7
source

Source: https://habr.com/ru/post/1446507/


All Articles