C#线程/锁定混乱

前端之家收集整理的这篇文章主要介绍了C#线程/锁定混乱前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有以下代码
  1. var items = new List<string> {"1","2","3"}; // 200 items
  2. foreach(var item in items) {
  3. ThreadPool.QueueUserWorkItem((DoWork),item);
  4. }
  5.  
  6. private void DoWork(object obj)
  7. {
  8. lock(this)
  9. {
  10. using(var sw = File.AppendText(@"C:\somepath.txt")
  11. {
  12. sw.WriteLine(obj);
  13. }
  14. }
  15. }

由于线程,出于某种原因,我得到了写入文件的200个项目的随机数. 60或127或有时只有3.如果我删除ThreadPool并只在原始foreach循环内写入,则所有200个项目都会成功写入.

不知道为什么会这样?

谢谢你的帮助.

解决方法

MSDN documentation on ThreadPool的以下注释说明了一切:

The threads in the managed thread pool are background threads. That is,their IsBackground properties are true. This means that a ThreadPool thread will not keep an application running after all foreground threads have exited.

您的应用程序只是在线程完成运行之前退出(通过到达Main的末尾).

猜你在找的C#相关文章