我的一位学生要求我创建一个示例来解释多线程。我想出了这个伪示例,它将生成线程,这些线程将循环随机次数并在循环时休眠。我通过使用 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();
任何想法将不胜感激。
最佳答案
只要所有电话process.Start
发生在同一个线程上,你不需要锁定字典,因为它不会在 LongProcess
内部启动的后台线程中访问。类(class)。这意味着:你的类(class) LongProcess
不是线程安全的,但在您当前的代码中这不是问题。
为了安全起见并避免锁定,您可以使用新的 ConcurrentDictionary<TKey, TValue>
来自 .NET4。
关于c# - 多线程示例 - 我需要锁定字典吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10209517/