Skip to content

Instantly share code, notes, and snippets.

@bojanrajkovic
Created June 19, 2012 22:58
Show Gist options
  • Save bojanrajkovic/2957032 to your computer and use it in GitHub Desktop.
Save bojanrajkovic/2957032 to your computer and use it in GitHub Desktop.
A bit of fun with Grand Central Dispatch...
using System;
using System.Threading.Tasks;
using MonoMac.CoreFoundation;
using MonoMac.AppKit;
using System.Threading;
namespace GCDTest
{
class MainClass
{
public static void Main (string[] args)
{
NSApplication.Init ();
var gcds = new GrandCentralDispatchTaskScheduler ();
var tf = new TaskFactory (gcds);
tf.StartNew (() => {
Console.WriteLine ("Hello, world.");
Console.WriteLine ("Is thread pool thread: {0}", Thread.CurrentThread.IsThreadPoolThread);
Console.WriteLine ("Dispatch queue: {0}", DispatchQueue.CurrentQueue.Label);
}).Wait (Timeout.Infinite);
Console.WriteLine ();
Task.Factory.StartNew (() => {
Console.WriteLine ("Hello, world from non-GCD task.");
Console.WriteLine ("Is thread pool thread: {0}", Thread.CurrentThread.IsThreadPoolThread);
Console.WriteLine ("Dispatch queue: {0}", DispatchQueue.CurrentQueue.Label);
}).Wait (Timeout.Infinite);
}
}
public class GrandCentralDispatchTaskScheduler : TaskScheduler
{
static readonly DispatchQueue gcdDispatchQueue = new DispatchQueue ("org.mono.tpl_dispatch_queue");
protected override System.Collections.Generic.IEnumerable<Task> GetScheduledTasks ()
{
throw new NotImplementedException ();
}
protected override void QueueTask (Task task)
{
gcdDispatchQueue.DispatchAsync (delegate {
TryExecuteTaskInline (task, false);
});
}
// TODO: Tasks cannot be dequeued.
protected override bool TryDequeue (Task task)
{
return false;
}
protected override bool TryExecuteTaskInline (Task task, bool taskWasPreviouslyQueued)
{
if (taskWasPreviouslyQueued && !TryDequeue (task))
return false;
return TryExecuteTask (task);
}
}
}
bojanrajkovic@dynamic-033 ~/C/O/G/G/b/Debug $ mono --debug GCDTest.exe
Hello, world.
Is thread pool thread: False
Dispatch queue: org.mono.tpl_dispatch_queue
Hello, world from non-GCD task.
Is thread pool thread: True
Dispatch queue: com.apple.root.default-overcommit-priority
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment