I was wondering what are the limitations of the background task called by a remote device. All I found in Microsoft's documentation was the generic limitation of background task which is 30 seconds.
But my simple test shows that it's not the case for an app service called from another device. (I'm not sure about regular app services though. I didn't include them in my test)
Here's my testing method:
I put this code to OnBackgroundActivated
of an app and registered a TimeTrigger
background task.
for (int i = 0; i < 100; i++)
{
Common.ToastFunctions.SendToast((i * 5).ToString() + " seconds");
await System.Threading.Tasks.Task.Delay(TimeSpan.FromSeconds(5));
}
(And I got deferral so task won't get closed unexpectedly because of await
operations)
I got toast notifications for 20-25 seconds and nothing after that. So the process was killed before 30 seconds which is in line with the official documentation.
Then I put the exact same code in RequestReceived
event of my AppServiceConnection
, and this code in OnBackgroundActivated
(which basically sets the RequestReceived
event and gets the deferral:
this._backgroundTaskDeferral = args.TaskInstance.GetDeferral();
args.TaskInstance.Canceled += OnTaskCanceled;
var details = args.TaskInstance.TriggerDetails as AppServiceTriggerDetails;
if (details?.Name == "com.ganjine") //Remote Activation
{
_appServiceconnection = details.AppServiceConnection;
_appServiceconnection.RequestReceived += OnRequestReceived;
_appServiceconnection.ServiceClosed += AppServiceconnection_ServiceClosed;
}
Then I created a connection and sent some data to this background task from another device (using Rome APIs)
This time, it didn't stop before 30 seconds. My loop was 100
iterations, and I got toasts indicating that the background task didn't stop and was able to run ~500 seconds.
But this was my loop, it might as well have continued even more with a longer loop.
Is this the expected behavior? What is the exact limitation of AppService background tasks called from a remote device?
Update: It seems that it's necessary for the remote app (who is calling this background task) to stay opened. (probably because the connection object should stay alive?). If I close it, the background app service will be terminated after a few seconds.