Dear Xamarin Developers,
I'm trying to write periodic background service using XF. I use following code for Android service part:
[Service] class GpsPositionBackgroundService : Service { private const string Tag = "[GpsPositionBackgroundService]"; private bool _isRunning; private Context _context; private Task _task; #region overrides public override IBinder OnBind(Intent intent) { return null; } public override void OnCreate() { _context = this; _isRunning = false; _task = new Task(DoWork); } public override void OnDestroy() { _isRunning = false; if (_task != null) { _task.Dispose(); } } public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId) { if (!_isRunning) { _isRunning = true; _task.Start(); } return StartCommandResult.Sticky; } #endregion private void DoWork() { try { Log.WriteLine(LogPriority.Info, Tag, "Started!"); // Do something... } catch (Exception e) { Log.WriteLine(LogPriority.Error, Tag, e.ToString()); } finally { StopSelf(); } } }
The code above works perfectly for some time and then I always got such exception on this line:
public override void OnDestroy() { _isRunning = false; if (_task != null) { _task.Dispose(); <-------- this line causes an exception } }
System.InvalidOperationException: A task may only be disposed if it is in a completion state (RanToCompletion, Faulted or Canceled).
Can anyone tell me how I could fix this? I'd be very grateful for any hint.
Thanks in advance!
Best regards
Krzysztof
Answers
so what state is your task in when this exception occurs?
See my posts here for an example on how to get location in the background. Note for Android O the service will need to be promoted to the foreground.
https://forums.xamarin.com/discussion/comment/289196#Comment_289196
@JulienRosen - The weird thing is the fact that the task is in RanToCompletion state.
Thanks!
Krzysztof
Thank you - I will have a look at your code.
Best regards
Krzysztof