using System; using System.Collections.Generic; using System.Linq; namespace Chernobyl.Threading { /// /// Represents a job that can be done by a worker. /// public class Job { /// /// An interface for working with work methods. /// public delegate void WorkMethod(); /// /// Constructor. /// /// The method to call when requested to do work. /// The name of this job. /// The estimated amount of time this job will take /// to complete in milliseconds. public Job(WorkMethod workMethod, string name, float estimatedJobLength) { TheWorkMethod = workMethod; JobLengthLog = new Queue(); JobLengthLogSize = 5; Name = name; JobLengthLog.Enqueue(estimatedJobLength); } /// /// Constructor /// /// The name of this job. /// The estimated amount of time this job will take /// to complete in milliseconds. public Job(string name, float estimatedJobLength) : this(DoNothingWorkMethod, name, estimatedJobLength) { } /// /// A method that does nothing. Used as placeholder so that /// another work method can be set later. /// static private void DoNothingWorkMethod() { } /// /// The function that is called to do this job. /// public void DoJob() { DateTime startTime = DateTime.Now; TheWorkMethod(); DateTime endTime = DateTime.Now; // calculate the amount of time it took to complete the job TimeSpan jobLength = endTime - startTime; // remove a length if we've reached the maximum size // and then add the length to the log if (JobLengthLog.Count == JobLengthLogSize) JobLengthLog.Dequeue(); JobLengthLog.Enqueue((float)jobLength.TotalMilliseconds); } /// /// Gets/sets the method called when this job is asked to do work. /// public WorkMethod TheWorkMethod {get; set;} /// /// Gets the average amount of time it takes for this job to be completed. /// public float AverageJobLength { get { if (JobLengthLog.Count == 0) return 1.0f; else return JobLengthLog.Average(); } } /// /// Gets/sets the length of the job length log. /// public uint JobLengthLogSize {get; set;} /// /// The name of this job. /// public string Name {get; set;} /// /// Gets the job length log. The job length log stores the /// recorded lengths of time of this job so that an average /// can be calculated. /// Queue JobLengthLog {get; set;} } }