Last active
January 30, 2026 11:34
-
-
Save drolevar/7adb90ed426ab57792682715f6635ab4 to your computer and use it in GitHub Desktop.
Typed context for ManagementObjectSearcher
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| internal static class ManagementObjectSearcherExtensions | |
| { | |
| private const string CONTEXT_KEY = "Context"; | |
| public static TContext GetContext<TContext>(this ObjectReadyEventArgs e) => GetContext<TContext>(e, out _); | |
| public static TContext GetContext<TContext>(this ProgressEventArgs e) => GetContext<TContext>(e, out _); | |
| public static TContext GetContext<TContext>(this CompletedEventArgs e) | |
| { | |
| var result = GetContext<TContext>(e, out var backHandle); | |
| backHandle.Free(); | |
| return result; | |
| } | |
| private static TContext GetContext<TContext>(ManagementEventArgs e, out GCHandle backHandle) | |
| { | |
| var context = (ManagementNamedValueCollection)e.Context; | |
| var ptr = (IntPtr)context[CONTEXT_KEY]; | |
| backHandle = GCHandle.FromIntPtr(ptr); | |
| var result = (TContext)backHandle.Target; | |
| return result; | |
| } | |
| public static ManagementObjectSearcher SetContext<TContext>(this ManagementObjectSearcher searcher, TContext context) | |
| { | |
| var options = searcher.Options; | |
| var ptr = GCHandle.Alloc(context); | |
| options.Context.Add(CONTEXT_KEY, GCHandle.ToIntPtr(ptr)); | |
| return searcher; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment