IDS peak ICV v1.3.0
Loading...
Searching...
No Matches
SafeHandles.cs
Go to the documentation of this file.
1using System.Runtime.InteropServices;
2
4
5internal static class SafeHandles
6{
7 public static IntPtr[] ExtractHandles<T>(IList<T> objects, Func<T, SafeHandle> handleSelector, out Action release)
8 {
9 var handles = new IntPtr[objects.Count];
10 var safeHandles = new List<SafeHandle>();
11
12 for (var i = 0; i < objects.Count; i++)
13 {
14 SafeHandle sh = handleSelector(objects[i]);
15 var added = false;
16
17 try
18 {
19 sh.DangerousAddRef(ref added);
20 }
21 catch (ObjectDisposedException)
22 {
23 throw new IcvInternalErrorException("Region has already been disposed.",
24 Types.peak_icv_status
25 .PEAK_ICV_STATUS_INVALID_HANDLE);
26 }
27
28 if (!added)
29 {
30 throw new IcvInternalErrorException("Failed to pin SafeHandle",
31 Types.peak_icv_status
32 .PEAK_ICV_STATUS_INTERNAL_ERROR);
33 }
34
35 handles[i] = sh.DangerousGetHandle();
36 safeHandles.Add(sh);
37 }
38
39 var released = 0;
40
41 release = () =>
42 {
43 if (Interlocked.Exchange(ref released, 1) != 0)
44 {
45 return;
46 }
47
48 foreach (SafeHandle? safeHandle in safeHandles)
49 {
50 safeHandle.DangerousRelease();
51 }
52 };
53
54 return handles;
55 }
56
57 public static IntPtr[] ExtractHandles<T>(IList<T> objects, out Action release) where T : IHasSafeHandle
58 {
59 return ExtractHandles(
60 objects,
61 obj => obj.Handle,
62 out release);
63 }
64}
65
66internal interface IHasSafeHandle
67{
68 SafeHandle Handle { get; }
69}
IDSImaging.Peak.ICV.Backend.IHasSafeHandle IHasSafeHandle