程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#基礎知識 >> C#讓對象不被系統自動回收

C#讓對象不被系統自動回收

編輯:C#基礎知識
Technorati 標簽: C#

 

我們在使用c#托管代碼時,內存地址和GC回收那不是我們關心的,CLR已經給我們暗箱操作。
但是如果我們在c#中調用了一個非托管代碼,比如vc的DLL,而且他有個回調函數,需要引用c#中的某個對象並操作,這時候你就得要小心了。
要是非托管代碼中用到得托管代碼那個對象被GC給回收了,這時候就會報內存錯誤。
所以我們就要把那個對象“釘”住(pin),讓它的內存地址固定,而不被垃圾回收掉,然後最後我們自己管理,自己釋放內存,這時候就需要GCHandle,來看個何問起上的例子:

 

public delegate bool CallBack(int handle, IntPtr param);
public class LibWrap
{
    [DllImport("user32.dll")]
    public static extern bool EnumWindows(CallBack cb, IntPtr param);
}

class Program
{
    static void Main(string[] args)
    {
        TextWriter tw = System.Console.Out;
        GCHandle gch = GCHandle.Alloc(tw);
        CallBack cewp = new CallBack(CaptureEnumWindowsProc);
        LibWrap.EnumWindows(cewp, (IntPtr)gch);
        gch.Free();
        Console.Read();
    }
    private static bool CaptureEnumWindowsProc(int handle, IntPtr param)
    {
        GCHandle gch = (GCHandle)param;
        TextWriter tw = (TextWriter)gch.Target;

        tw.WriteLine(handle);
        return true;
    }
}

對上面的代碼,略加解釋:gch 會釘住(pin)tw這個對象,使其不受GC管理,告訴它,以後你崩管我,我也不用給你上稅,其實管理權已經給gch,通過free來釋放內存。
這種情況主要用在托管和非托管代碼交互的時候,防止內存洩露來使用GCHandle。

另也可以使用GC.KeepAlive 方法(引用msdn)
KeepAlive 方法的目的是確保對對象的引用存在,該對象有被垃圾回收器過早回收的危險。這種現象可能發生的一種常見情形是,當在托管代碼或數據中已沒有對該對象的引用,但該對象仍然在非托管代碼(如 Win32 API、非托管 DLL 或使用 COM 的方法)中使用。
下面是例子:

using System;
using System.Threading;
using 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 class MyWin32
{
    // Declare the SetConsoleCtrlHandler function   
    // as external and receiving a delegate.     
    [DllImport("Kernel32")]
    public static extern Boolean SetConsoleCtrlHandler(HandlerRoutine Handler,
        Boolean Add);

    // A delegate type to be used as the handler routine   
    // for SetConsoleCtrlHandler.  
    public delegate Boolean HandlerRoutine(CtrlTypes CtrlType);

    // An enumerated type for the control messages   
    // sent to the handler routine.  
    public enum CtrlTypes
    {
        CTRL_C_EVENT = 0,
        CTRL_BREAK_EVENT,
        CTRL_CLOSE_EVENT,
        CTRL_LOGOFF_EVENT = 5,
        CTRL_SHUTDOWN_EVENT
    }
}

public 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.";
                break;
            case MyWin32.CtrlTypes.CTRL_BREAK_EVENT:
                message = "A CTRL_BREAK_EVENT was raised by the user.";
                break;
            case MyWin32.CtrlTypes.CTRL_CLOSE_EVENT:
                message = "A CTRL_CLOSE_EVENT was raised by the user.";
                break;
            case MyWin32.CtrlTypes.CTRL_LOGOFF_EVENT:
                message = "A CTRL_LOGOFF_EVENT was raised by the user.";
                break;
            case MyWin32.CtrlTypes.CTRL_SHUTDOWN_EVENT:
                message = "A CTRL_SHUTDOWN_EVENT was raised by the user.";
                break;
        }

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

        return true;
    }

    public static void Main()
    {
        // Use interop to set a console control handler.  
        MyWin32.HandlerRoutine hr = new 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.  
        GC.Collect();
        GC.WaitForPendingFinalizers();
        GC.Collect();

        Thread.Sleep(10000);

        // 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);
        Console.Read();
    }
}
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved