budnhead/org.budnhead/tools/JobThreader.cs

84 lines
1.5 KiB
C#

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