Forum Xamarin.Forms
We are excited to announce that the Xamarin Forums are moving to the new Microsoft Q&A experience. Q&A is the home for technical questions and answers at across all products at Microsoft now including Xamarin!

We encourage you to head over to Microsoft Q&A for .NET for posting new questions and get involved today.

Periodic Background Service task disposing exception

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

Sign In or Register to comment.