When is it acceptable to call GC.Collect?

前端 未结 24 2441
挽巷
挽巷 2020-11-22 08:54

The general advise is that you should not call GC.Collect from your code, but what are the exceptions to this rule?

I can only think of a few very speci

24条回答
  •  情深已故
    2020-11-22 09:24

    You should try to avoid using GC.Collect() since its very expensive. Here is an example:

            public void ClearFrame(ulong timeStamp)
        {
            if (RecordSet.Count <= 0) return;
            if (Limit == false)
            {
                var seconds = (timeStamp - RecordSet[0].TimeStamp)/1000;
                if (seconds <= _preFramesTime) return;
                Limit = true;
                do
                {
                    RecordSet.Remove(RecordSet[0]);
                } while (((timeStamp - RecordSet[0].TimeStamp) / 1000) > _preFramesTime);
            }
            else
            {
                RecordSet.Remove(RecordSet[0]);
    
            }
            GC.Collect(); // AVOID
        }
    

    TEST RESULT: CPU USAGE 12%

    When you change to this:

            public void ClearFrame(ulong timeStamp)
        {
            if (RecordSet.Count <= 0) return;
            if (Limit == false)
            {
                var seconds = (timeStamp - RecordSet[0].TimeStamp)/1000;
                if (seconds <= _preFramesTime) return;
                Limit = true;
                do
                {
                    RecordSet[0].Dispose(); //  Bitmap destroyed!
                    RecordSet.Remove(RecordSet[0]);
                } while (((timeStamp - RecordSet[0].TimeStamp) / 1000) > _preFramesTime);
            }
            else
            {
                RecordSet[0].Dispose(); //  Bitmap destroyed!
                RecordSet.Remove(RecordSet[0]);
    
            }
            //GC.Collect();
        }
    

    TEST RESULT: CPU USAGE 2-3%

提交回复
热议问题