我有這樣一段代碼(從諾基亞PC連接3.2示例代碼,在C#):運行「GC.Collect的」修復我的崩潰,但我不明白爲什麼
DAContentAccessDefinitions.CA_FOLDER_INFO folderInfo =
new DAContentAccessDefinitions.CA_FOLDER_INFO();
folderInfo.iSize = Marshal.SizeOf(folderInfo); //(32)
IntPtr bufItem = Marshal.AllocHGlobal(folderInfo.iSize);
//I often get a AccessViolationException on the following line
Marshal.StructureToPtr(folderInfo, bufItem, true);
如果我在開始時運行GC.Collect()
,然後我沒有收到AccessViolationException
。但除非必要,否則我不想減慢此功能。我試過把GC.Keepalive
放在不同的地方,但沒有成功。
CA_FOLDER_INFO
被定義爲:
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
public struct CA_FOLDER_INFO
{
public int iSize;
public int iFolderId;
public int iOptions;
public string pstrName;
public string pstrPath;
public int iSubFolderCount;
public IntPtr pSubFolders;
public IntPtr pParent;
}
我不這樣做,在這種情況下,都要求使用字符串,並改變它們的定義,以IntPtr
似乎使異常消失。
這是怎麼回事,防止異常的正確方法是什麼?
不要忘記在一個try-finally包裝中,當你完成bufItem時調用Marshal.FreeHGlobal。 – sisve 2009-06-15 10:32:36