开发者

Should I call GC.Collect in custom thread pool?

I have created thread pool which have 5 threads. Both of them will start when my application start up. The problem is I created so many objects in thread loop call back function on each threads, and the memory is increase by second when app running, this is thread loop call back function:

void ThreadLoop(){

   while(true){

         var checkItems = _workItems.Where(w=>w.ActivedTime > 3).ToList();

         foreach(var i in checkItems){

             _workItems[i.Id].ActivedTime = 0;

             _workItems[i.Id].ExecutePostBack();

         }

         //Recreate new _workItems dictionary

        _workItems = _workItems.Where(w=>w.ActivedT开发者_如何学运维ime > 0).ToDictionary();

        // Sleep thread to free up momory

        Thread.Sleep(1000);

        // Call Grab collector free memory

        GC.Collect();

   }

}

I'm confusing that, is calling GC.Collect() on each threads like that good or bad ? Dose it cause bad performence ?


If you have to ask yourself whether to call GC.Collect, the answer is almost definitely "no". The GC is designed to run automatically as needed, and invoking it yourself says "I know better than the GC itself about when it should run". Anyone who doesn't know the details of GC is more likely to be wrong than right, and will actually make things worse.

The best course of action is almost always to let GC take care of itself.


It is ill-advised to call GC.Collect unless you really need to such as in some corner-cases with COM interop. At best, you're invoking the GC more than it needs to, at worst you could be promoting otherwise short-lived objects into higher GC generations which makes them more expensive to clean up later.

The GC is triggered upon memory pressure when memory is allocated, not time. So it's not uncommon to see a temporary spike in memory that hangs around for a long time if you're no longer allocating new objects. In this case it might be ok to call GC.Collect but I'd avoid calling it in a loop if you can.


You don't need to call GC.Collect() in most cases, except in rare situations (and I think yours is not). See here for more explanation: http://blogs.msdn.com/b/ricom/archive/2004/11/29/271829.aspx

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜