我有以下代码:
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 aThreadPool
thread will not keep an application running after all foreground threads have exited.
您的应用程序只是在线程完成运行之前退出(通过到达Main的末尾).