学生の 1 人から、マルチスレッドを説明する例を作成するように依頼されました。私は、ランダムな回数ループし、ループ中にスリープするスレッドを生成するこの疑似例を思いつきました。各スレッドを識別するために Guid を使用するディクショナリを介して、これらのスレッドを追跡しています。
ディクショナリは、これらのスレッドを監視し、場合によってはそれらを「殺す」ために使用されるページで使用できます。
これは合理的に見えますか:
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();
}
}
このクラスの使用方法は次のとおりです。
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();
任意のアイデアをいただければ幸いです。