Skip to content

Instantly share code, notes, and snippets.

@Sakurina
Created June 24, 2010 21:04
Show Gist options
  • Save Sakurina/451978 to your computer and use it in GitHub Desktop.
Save Sakurina/451978 to your computer and use it in GitHub Desktop.
naïve implementation of something like Grand Central Dispatch, in C#
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
public struct DispatchAction {
public Action action;
public DispatchActionType type;
public DispatchAction(Action a, DispatchActionType t) {
action = a;
type = t;
}
}
public enum DispatchActionType {
Async,
Sync
};
public class DispatchQueue {
private Thread _thread;
private Queue<DispatchAction> _queue;
private Mutex mut;
public DispatchQueue() {
_queue = new Queue<DispatchAction>();
_thread = new Thread(new ThreadStart(RunLoop));
mut = new Mutex();
}
private void RunLoop() {
while (_queue.Count > 0) {
mut.WaitOne();
DispatchAction a = _queue.Dequeue();
mut.ReleaseMutex();
a.action();
}
}
public void AddAction(Action a, DispatchActionType t) {
mut.WaitOne();
_queue.Enqueue(new DispatchAction(a, t));
if (!_thread.IsAlive)
_thread.Start();
mut.ReleaseMutex();
}
}
public class Dispatch {
public static DispatchQueue Queue_Create() {
return new DispatchQueue();
}
public static void Async(DispatchQueue q, Action a) {
q.AddAction(a, DispatchActionType.Async);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment