Skip to content

Instantly share code, notes, and snippets.

@vbfox
Created January 15, 2012 22:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vbfox/1617651 to your computer and use it in GitHub Desktop.
Save vbfox/1617651 to your computer and use it in GitHub Desktop.
An implementation of a TaskScheduler running code on a thread designated by an Android.OS.Handler (MonoDroid)
namespace BlackFox
{
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Android.OS;
/// <summary>
/// Provides a <see cref="TaskScheduler"/> using an android <see cref="Handler"/> to run the tasks.
/// </summary>
public class AndroidTaskScheduler : TaskScheduler
{
readonly Handler handler;
/// <summary>Initializes a new instance of the AndroidTaskScheduler class.</summary>
/// <remarks>This constructors defaults to using the android handler associated with the current thread.</remarks>
public AndroidTaskScheduler()
{
handler = new Handler();
}
/// <summary>Initializes a new instance of the AndroidTaskScheduler class.</summary>
/// <param name="handler">The android Handler that will be used to run the tasks.</param>
public AndroidTaskScheduler(Handler handler)
{
if (handler == null) throw new ArgumentNullException("handler");
this.handler = handler;
}
protected override IEnumerable<Task> GetScheduledTasks()
{
// A class derived from TaskScheduler implements this method in order to support integration with
// debuggers. We don't support such integration ;-)
throw new NotSupportedException();
}
protected override void QueueTask(Task task)
{
handler.Post(() => TryExecuteTask(task));
}
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
{
var currentLooper = Looper.MyLooper();
if (currentLooper == null || !currentLooper.Equals(handler.Looper)) return false;
if (taskWasPreviouslyQueued) return false;
return TryExecuteTask(task);
}
public override int MaximumConcurrencyLevel
{
get
{
return 1;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment