【发布时间】:2011-07-18 05:05:44
【问题描述】:
我一直在阅读新的并发集合,尤其是 ConcurrentBag 引起了我的注意。由于 ConcurrentBag 内部在每个单独的线程上保存了一个本地集合,使用它来跟踪项目,这意味着当线程本身超出范围时,它仍然会被 ConcurrentBag 在内存中引用。这又意味着线程占用的内存以及本机资源? (请原谅我不知道 .NET 线程对象的确切内部工作原理)
我可以假设一个用例,其中您有 1 个全局 ConcurrentBack 用于多线程 Web 服务,您有很多客户端添加任务。这些任务由线程池上的线程添加。现在线程池是管理线程的一种非常有效的方式,但它确实会根据工作量删除和创建线程。因此,这样的 web 服务有时会遇到麻烦,因为底层包仍然引用许多应该被销毁的线程。
我创建了一个快速应用来测试这种行为:
static ConcurrentBag<int> bag = new ConcurrentBag<int>();
static void FillBag() { for (int i = 0; i < 100; i++) { bag.Add(i); } }
static void PrintState() { Console.WriteLine("Bag size is: {0}", bag.Count); }
static void Main(string[] args)
{
var remote = new Thread(x =>
{
FillBag();
PrintState();
});
// empty bag
PrintState();
// first 100 items are added on main thread
FillBag();
PrintState();
// second 100 items are added on remote thread
remote.Start();
remote.Join();
// since the remote thread is gone out of scope, what happened to its local storage which is part of the bag?
PrintState();
// now force a cleanup
WeakReference weakRemoteReference = new WeakReference(remote);
remote = null;
GC.Collect();
GC.WaitForPendingFinalizers();
// Now check if the thread still exists
if (weakRemoteReference.IsAlive)
Console.WriteLine("Remote thread still exists");
PrintState();
Console.ReadLine();
输出证实了我的故事:
Bag size is: 0
Bag size is: 100
Bag size is: 200
Bag size is: 200
Remote thread still exists
Bag size is: 200
这种行为是意料之中的吗?是我在测试中犯了错误还是可以将其视为设计缺陷?
【问题讨论】:
-
请注意,我将远程线程命名为超出范围,当然它仍在范围内,应该说:“自从远程线程完成”
标签: .net concurrency