C#线程/锁定混乱 [英] C# Threading/Lock confusion

查看:113
本文介绍了C#线程/锁定混乱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

var items = new List<string> {"1", "2", "3"}; // 200 items
foreach(var item in items) {
  ThreadPool.QueueUserWorkItem((DoWork), item);
}

private void DoWork(object obj)
{
  lock(this)
  {
    using(var sw = File.AppendText(@"C:\somepath.txt")
    {
      sw.WriteLine(obj);
    }
  }
}

由于螺纹的,由于某种原因,我得到写出到文件中的200个项目的一个随机数。60,或127,或有时只3.如果我删除线程池,只是写原来的foreach循环内,所有200个项目被成功写入。

Because of the threading, for some reason, I get a random number of the 200 items written out to the file. 60 or 127 or sometimes only 3. If I remove the ThreadPool and just write inside the original foreach loop, all 200 items are written successfully.

不知道为什么出现这种情况?

Not sure why this occurs?

感谢您的帮助。

推荐答案

从的MSDN关于线程池 文档说明了一切:

The following note from MSDN documentation on ThreadPool says it all:

在托管线程池中的线程是后台线程,也就是说,它们的的IsBackground 属性是真实的。这意味着线程池线程不会让应用程序运行的所有前台线程都退出后,

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.

您的应用程序只需(由达的结尾)你的线程之前完成运行退出。

Your application simply exits (by reaching end of Main) before your threads finish running.

这篇关于C#线程/锁定混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆