I was asked by one of my students to create an example which would explain multi-threading. I came up with this pseudo example which will spawn threads which will loop a random number of times and sleep while looping. I am keeping track of these threads via a Dictionary which uses a Guid to identify each thread.
The Dictionary could be used on pages used to monitor these threads and possibly "kill" them.
Does this look reasonable:
public class LongProcess
{
public static Dictionary<Guid, LongProcess> Monitor = new Dictionary<Guid, LongProcess>();
public Guid Id { get; set; }
public int Iterations { get; set; }//number of loops
public int SleepFactor { get; set; }//rest period while looping
public int CompletedIterations { get; set; }//number of completed loops
void Process()
{
for(var i = 0 ; i < Iterations; i++)
{
Thread.Sleep(1000*SleepFactor);
SleepFactor = new Random(DateTime.Now.Millisecond).Next(1, 5);
this.CompletedIterations++;
}
}
public void Start()
{
Monitor.Add(Id, this);
var thread = new Thread(new ThreadStart(Process));
thread.Start();
}
}
Here is how this class would be used:
var id = Guid.NewGuid();
var rnd = new Random(DateTime.Now.Millisecond);
var process = new LongProcess
{
Iterations = rnd.Next(5, 20),
SleepFactor = rnd.Next(1, 5),
Id = id
};
process.Start();
any ideas would be appreciated.