When is it acceptable to call GC.Collect?

前端 未结 24 2442
挽巷
挽巷 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:23

    Another reason is when you have a SerialPort opened on a USB COM port, and then the USB device is unplugged. Because the SerialPort was opened, the resource holds a reference to the previously connected port in the system's registry. The system's registry will then contain stale data, so the list of available ports will be wrong. Therefore the port must be closed.

    Calling SerialPort.Close() on the port calls Dispose() on the object, but it remains in memory until garbage collection actually runs, causing the registry to remain stale until the garbage collector decides to release the resource.

    From https://stackoverflow.com/a/58810699/8685342:

    try
    {
        if (port != null)
            port.Close(); //this will throw an exception if the port was unplugged
    }
    catch (Exception ex) //of type 'System.IO.IOException'
    {
        System.GC.Collect();
        System.GC.WaitForPendingFinalizers();
    }
    
    port = null;
    

提交回复
热议问题