RuntimeHelpers クラス
アセンブリ: mscorlib (mscorlib.dll 内)


PrepareConstrainedRegions メソッドを使用して、ハンドルを確実に設定する方法を次のコード例に示します。ハンドルを指定した既存のハンドルに確実に設定するには、ネイティブ ハンドルの割り当てと SafeHandle オブジェクト内でのそのハンドルの以降の記録を分離不可能な状態にすることが必要です。これらの操作間でエラーが発生すると (スレッドの中止やメモリ不足の例外によるエラーなど)、ネイティブ ハンドルがリークされることになります。PrepareConstrainedRegions メソッドを使用すると、ハンドルのリークを確実に防ぐことができます。
<StructLayout(LayoutKind.Sequential)> _ Structure MyStruct Public m_outputHandle As IntPtr End Structure 'MyStruct NotInheritable Class MySafeHandle Inherits SafeHandle ' Called by P/Invoke when returning SafeHandles Public Sub New() MyBase.New(IntPtr.Zero, True) End Sub Public Function AllocateHandle() As MySafeHandle ' Allocate SafeHandle first to avoid failure later. Dim sh As New MySafeHandle() RuntimeHelpers.PrepareConstrainedRegions() Try Finally Dim myStruct As New MyStruct() NativeAllocateHandle(myStruct) sh.SetHandle(myStruct.m_outputHandle) End Try Return sh End Function
[StructLayout(LayoutKind.Sequential)] struct MyStruct { public IntPtr m_outputHandle; } sealed class MySafeHandle : SafeHandle { // Called by P/Invoke when returning SafeHandles public MySafeHandle() : base(IntPtr.Zero, true) { } public MySafeHandle AllocateHandle() { // Allocate SafeHandle first to avoid failure later. MySafeHandle sh = new MySafeHandle(); RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { MyStruct myStruct = new MyStruct(); NativeAllocateHandle(ref myStruct); sh.SetHandle(myStruct.m_outputHandle); } return sh; }

System.Runtime.CompilerServices.RuntimeHelpers


Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


- RuntimeHelpers クラスのページへのリンク