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.
As long as all calls to
process.Startoccur on the same thread, you don’t need to lock the dictionary, because it isn’t accessed in the background threads that are started inside theLongProcessclass. That means: Your classLongProcessis not thread safe, but in your current code this isn’t a problem.To be on the safe side and to avoid locking, you can use the new
ConcurrentDictionary<TKey, TValue>from .NET4.