Skip to content

Instantly share code, notes, and snippets.

@drolevar
Last active January 30, 2026 11:34
Show Gist options
  • Select an option

  • Save drolevar/7adb90ed426ab57792682715f6635ab4 to your computer and use it in GitHub Desktop.

Select an option

Save drolevar/7adb90ed426ab57792682715f6635ab4 to your computer and use it in GitHub Desktop.
Typed context for ManagementObjectSearcher
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