using System; using System.Threading; using System.Collections.Generic; namespace org.budnhead.tools { public delegate T JobDelegate(); public class JobThreader { Thread workerThread; List queuedJobs; public JobThreader() { workerThread = Thread.CurrentThread; queuedJobs = new List(); } public JobThreader(Thread workerThread){ this.workerThread = workerThread; queuedJobs = new List(); } public void execute(){ Monitor.Enter(queuedJobs); foreach (Job j in queuedJobs){ j.execute(); } queuedJobs.Clear(); Monitor.PulseAll(queuedJobs); Monitor.Exit(queuedJobs); } public T execute(JobDelegate jobDelegate) where T : class{ if (workerThread.Equals(Thread.CurrentThread)){ return jobDelegate(); } else { return Enqueue(jobDelegate); } } private T Enqueue(JobDelegate jobDelegate) where T : class { Job job; Monitor.Enter(queuedJobs); job = new Job(jobDelegate); queuedJobs.Add(job); Monitor.Wait(queuedJobs); Monitor.Exit(queuedJobs); return job.Result; } public abstract class Job{ public virtual void execute(){ } } public class Job : Job{ T result; JobDelegate jobDelegate; public Job(JobDelegate jobDelegate){ this.jobDelegate = jobDelegate; } public override void execute() { this.result = this.jobDelegate(); } public T Result { get { return this.result; } } } } }