Domanda

I am using a background thread to make an async call to the web service and return the results.When the background thread is running and my app gets deactivated, say the user presses the home button, How do I handle it?

private async void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
   //What should I do here?
}

I understand from the following blog http://www.wintellect.com/blogs/jgarland/proceed-with-caution---windows-phone-8-app-lifecycle-events-vs-async-methods that I cannot await till the background threads complete in the deactivated method.Also it suggests using synchronous calls.In case I have to cancel my background thread inside deactivated event,How do I find which background thread is running at the moment?In every page where web service is called , a background thread is used.Is there any way to resume a background thread after app is activated again?

È stato utile?

Soluzione

You are right that when your App is deactivated then all processes are stopped - MSDN source:

When the user navigates forward, away from an app, after the Deactivated event is raised, the operating system will attempt to put the app into a dormant state. In this state, all of the application’s threads are stopped and no processing takes place, but the application remains intact in memory.

In your deactivated event you should invoke Cancel request to all your background threads. If you are using aync-await then you can equip those methods with CancellationTokenSource. Here is some more about this: Enabling Progress and Cancellation in Async, Cancel an Async Task or a List of Tasks , and you can find lot of information on Stephen Cleary blog.

As for the question to know which Task is running I think you can use this CancellationTokenSource to check it - if it isn't null then it means that your bacground thread is working.

And as for reacivating your method - everything depends on your code and what that method perform. If you are downloading a group of files then you can remember which are downloaded and after activation call method downloading the rest. If you perform some calculation then you can remember the place where the method stopped and try to resume further calculations. Thought it can be sometimes hard. And you must remember that you have limited time to 10 seconds:

You should not wait until the Deactivated event occurs to store this data. Remember that all application lifecycle events enforce a limit of 10 seconds for an application to complete any tasks.


About other possibilities:

If you want to perform some actions in background proces - then you can use Background agents and Background transfers if you want to download a file. There is also Background audio, but I suppose you are not asking about it.

If you want your app to stay in foreground when lock screen is engaged then you can Deactivate Idle Detection.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top