GC::KeepAlive Method (Object^)


The .NET API Reference documentation has a new home. Visit the .NET API Browser on docs.microsoft.com to see the new experience.

References the specified object, which makes it ineligible for garbage collection from the start of the current routine to the point where this method is called.

Namespace:   System
Assembly:  mscorlib (in mscorlib.dll)

static void KeepAlive(
	Object^ obj


Type: System::Object^

The object to reference.

The purpose of the KeepAlive method is to ensure the existence of a reference to an object that is at risk of being prematurely reclaimed by the garbage collector. A common scenario where this might happen is when there are no references to the object in managed code or data, but the object is still in use in unmanaged code such as Win32 APIs, unmanaged DLLs, or methods using COM.

This method references the obj parameter, making that object ineligible for garbage collection from the start of the routine to the point, in execution order, where this method is called. Code this method at the end, not the beginning, of the range of instructions where obj must be available.

The KeepAlive method performs no operation and produces no side effects other than extending the lifetime of the object passed in as a parameter.

The following code example creates an object at the beginning of its Main method and does not refer to the object again until the end, when the KeepAlive method is called. The object persists for the 30-second duration of the Main method, despite calls to the Collect and WaitForPendingFinalizers methods.

using namespace System;
using namespace System::Threading;
using namespace System::Runtime::InteropServices;

// A simple class that exposes two static Win32 functions.
// One is a delegate type and the other is an enumerated type.
public ref class MyWin32

   // An enumerated type for the control messages sent to the handler routine.
   enum class CtrlTypes
      CTRL_C_EVENT = 0,

   delegate Boolean HandlerRoutine(    // A delegate type to be used as the Handler Routine for SetConsoleCtrlHandler.
   CtrlTypes CtrlType );

   // Declare the SetConsoleCtrlHandler function as external and receiving a delegate.

   static Boolean SetConsoleCtrlHandler( HandlerRoutine^ Handler, Boolean Add );

public ref class MyApp

   // A private static handler function in the MyApp class.
   static Boolean Handler( MyWin32::CtrlTypes CtrlType )
      String^ message = "This message should never be seen!";

      // A switch to handle the event type.
      switch ( CtrlType )
         case MyWin32::CtrlTypes::CTRL_C_EVENT:
            message = "A CTRL_C_EVENT was raised by the user.";

         case MyWin32::CtrlTypes::CTRL_BREAK_EVENT:
            message = "A CTRL_BREAK_EVENT was raised by the user.";

         case MyWin32::CtrlTypes::CTRL_CLOSE_EVENT:
            message = "A CTRL_CLOSE_EVENT was raised by the user.";

         case MyWin32::CtrlTypes::CTRL_LOGOFF_EVENT:
            message = "A CTRL_LOGOFF_EVENT was raised by the user.";

         case MyWin32::CtrlTypes::CTRL_SHUTDOWN_EVENT:
            message = "A CTRL_SHUTDOWN_EVENT was raised by the user.";

      // Use interop to display a message for the type of event.
      Console::WriteLine( message );
      return true;

   static void Test()

      // Use interop to set a console control handler.
      MyWin32::HandlerRoutine^ hr = gcnew MyWin32::HandlerRoutine( Handler );
      MyWin32::SetConsoleCtrlHandler( hr, true );

      // Give the user some time to raise a few events.
      Console::WriteLine( "Waiting 30 seconds for console ctrl events..." );

      // The Object hr is not referred to again.
      // The garbage collector can detect that the object has no
      // more managed references and might clean it up here while
      // the unmanaged SetConsoleCtrlHandler method is still using it.
      // Force a garbage collection to demonstrate how the hr
      // object will be handled.
      Thread::Sleep( 30000 );

      // Display a message to the console when the unmanaged method
      // has finished its work.
      Console::WriteLine( "Finished!" );

      // Call GC::KeepAlive(hr) at this point to maintain a reference to hr.
      // This will prevent the garbage collector from collecting the
      // object during the execution of the SetConsoleCtrlHandler method.
      GC::KeepAlive( hr );


int main()

Universal Windows Platform
Available since 8
.NET Framework
Available since 1.1
Portable Class Library
Supported in: portable .NET platforms
Available since 2.0
Windows Phone Silverlight
Available since 7.0
Windows Phone
Available since 8.1
Return to top