加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C#线程/锁定混乱

发布时间:2020-12-15 08:38:31 所属栏目:百科 来源:网络整理
导读:我有以下代码: var items = new Liststring {"1","2","3"}; // 200 itemsforeach(var item in items) { ThreadPool.QueueUserWorkItem((DoWork),item);}private void DoWork(object obj){ lock(this) { using(var sw = File.AppendText(@"C:somepath.txt")
我有以下代码:
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.如果我删除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的末尾).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读