Handling simultaneous service requests
We may require a single service to be able to handle multiple requests from multiple sources simultaneously.
How to do it...
If we want a service to be able to handle multiple requests simultaneously, we inherit from the Service
type, which provides the required features:
We first need a type that inherits from
Service
:[Service] public class XamarinService : Service { public override StartCommandResult OnStartCommand( Intent intent, StartCommandFlags flags, int startId) { return StartCommandResult.Sticky; } public override IBinder OnBind(Intent intent) { return null; } }
Now, we can create a method that handles multiple requests:
private int started = 0; private async void ProcessRequest() { started++; await Task.Run (() => { // do the work for this particular request // ... StopSelf (startId); }); started--; if (started == 0) StopSelf(); }
Each time the
OnStartCommand()
method is invoked, we can start a new...