/
ManagementEventWatcher.cs
768 lines (680 loc) · 30.4 KB
/
ManagementEventWatcher.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Threading;
namespace System.Management
{
/// <summary>
/// <para>Represents the method that will handle the <see cref='System.Management.ManagementEventWatcher.EventArrived'/> event.</para>
/// </summary>
public delegate void EventArrivedEventHandler(object sender, EventArrivedEventArgs e);
/// <summary>
/// <para>Represents the method that will handle the <see cref='System.Management.ManagementEventWatcher.Stopped'/> event.</para>
/// </summary>
public delegate void StoppedEventHandler(object sender, StoppedEventArgs e);
//CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC//
/// <summary>
/// <para> Subscribes to temporary event notifications
/// based on a specified event query.</para>
/// </summary>
/// <example>
/// <code lang='C#'>using System;
/// using System.Management;
///
/// // This example demonstrates how to subscribe to an event using the ManagementEventWatcher object.
/// class Sample_ManagementEventWatcher
/// {
/// public static int Main(string[] args) {
///
/// //For the example, we'll put a class into the repository, and watch
/// //for class deletion events when the class is deleted.
/// ManagementClass newClass = new ManagementClass();
/// newClass["__CLASS"] = "TestDeletionClass";
/// newClass.Put();
///
/// //Set up an event watcher and a handler for the event
/// ManagementEventWatcher watcher = new ManagementEventWatcher(
/// new WqlEventQuery("__ClassDeletionEvent"));
/// MyHandler handler = new MyHandler();
/// watcher.EventArrived += new EventArrivedEventHandler(handler.Arrived);
///
/// //Start watching for events
/// watcher.Start();
///
/// // For the purpose of this sample, we delete the class to trigger the event
/// // and wait for two seconds before terminating the consumer
/// newClass.Delete();
///
/// System.Threading.Thread.Sleep(2000);
///
/// //Stop watching
/// watcher.Stop();
///
/// return 0;
/// }
///
/// public class MyHandler {
/// public void Arrived(object sender, EventArrivedEventArgs e) {
/// Console.WriteLine("Class Deleted = " +
/// ((ManagementBaseObject)e.NewEvent["TargetClass"])["__CLASS"]);
/// }
/// }
/// }
/// </code>
/// <code lang='VB'>Imports System
/// Imports System.Management
///
/// ' This example demonstrates how to subscribe an event using the ManagementEventWatcher object.
/// Class Sample_ManagementEventWatcher
/// Public Shared Sub Main()
///
/// ' For the example, we'll put a class into the repository, and watch
/// ' for class deletion events when the class is deleted.
/// Dim newClass As New ManagementClass()
/// newClass("__CLASS") = "TestDeletionClass"
/// newClass.Put()
///
/// ' Set up an event watcher and a handler for the event
/// Dim watcher As _
/// New ManagementEventWatcher(New WqlEventQuery("__ClassDeletionEvent"))
/// Dim handler As New MyHandler()
/// AddHandler watcher.EventArrived, AddressOf handler.Arrived
///
/// ' Start watching for events
/// watcher.Start()
///
/// ' For the purpose of this sample, we delete the class to trigger the event
/// ' and wait for two seconds before terminating the consumer
/// newClass.Delete()
///
/// System.Threading.Thread.Sleep(2000)
///
/// ' Stop watching
/// watcher.Stop()
///
/// End Sub
///
/// Public Class MyHandler
/// Public Sub Arrived(sender As Object, e As EventArrivedEventArgs)
/// Console.WriteLine("Class Deleted = " & _
/// CType(e.NewEvent("TargetClass"), ManagementBaseObject)("__CLASS"))
/// End Sub
/// End Class
/// End Class
/// </code>
/// </example>
//CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC//
[ToolboxItem(false)]
public class ManagementEventWatcher : Component
{
//fields
private ManagementScope scope;
private EventQuery query;
private EventWatcherOptions options;
private IEnumWbemClassObject enumWbem;
private IWbemClassObjectFreeThreaded[] cachedObjects; //points to objects currently available in cache
private uint cachedCount; //says how many objects are in the cache (when using BlockSize option)
private uint cacheIndex; //used to walk the cache
private SinkForEventQuery sink; // the sink implementation for event queries
private readonly WmiDelegateInvoker delegateInvoker;
//Called when IdentifierChanged() event fires
private void HandleIdentifierChange(object sender,
IdentifierChangedEventArgs e)
{
// Invalidate any sync or async call in progress
Stop();
}
//default constructor
/// <overload>
/// Initializes a new instance of the <see cref='System.Management.ManagementEventWatcher'/> class.
/// </overload>
/// <summary>
/// <para> Initializes a new instance of the <see cref='System.Management.ManagementEventWatcher'/> class. For further
/// initialization, set the properties on the object. This is the default constructor.</para>
/// </summary>
public ManagementEventWatcher() : this((ManagementScope)null, null, null) { }
//parameterized constructors
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.Management.ManagementEventWatcher'/> class when given a WMI event query.</para>
/// </summary>
/// <param name='query'>An <see cref='System.Management.EventQuery'/> object representing a WMI event query, which determines the events for which the watcher will listen.</param>
/// <remarks>
/// <para>The namespace in which the watcher will be listening for
/// events is the default namespace that is currently set.</para>
/// </remarks>
public ManagementEventWatcher(
EventQuery query) : this(null, query, null) { }
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.Management.ManagementEventWatcher'/> class when given a WMI event query in the
/// form of a string.</para>
/// </summary>
/// <param name='query'> A WMI event query, which defines the events for which the watcher will listen.</param>
/// <remarks>
/// <para>The namespace in which the watcher will be listening for
/// events is the default namespace that is currently set.</para>
/// </remarks>
public ManagementEventWatcher(
string query) : this(null, new EventQuery(query), null) { }
/// <summary>
/// <para> Initializes a new instance of the <see cref='System.Management.ManagementEventWatcher'/>
/// class that listens for events conforming to the given WMI event query.</para>
/// </summary>
/// <param name='scope'>A <see cref='System.Management.ManagementScope'/> object representing the scope (namespace) in which the watcher will listen for events.</param>
/// <param name=' query'>An <see cref='System.Management.EventQuery'/> object representing a WMI event query, which determines the events for which the watcher will listen.</param>
public ManagementEventWatcher(
ManagementScope scope,
EventQuery query) : this(scope, query, null) { }
/// <summary>
/// <para> Initializes a new instance of the <see cref='System.Management.ManagementEventWatcher'/>
/// class that listens for events conforming to the given WMI event query. For this
/// variant, the query and the scope are specified as strings.</para>
/// </summary>
/// <param name='scope'> The management scope (namespace) in which the watcher will listen for events.</param>
/// <param name=' query'> The query that defines the events for which the watcher will listen.</param>
public ManagementEventWatcher(
string scope,
string query) : this(new ManagementScope(scope), new EventQuery(query), null) { }
/// <summary>
/// <para> Initializes a new instance of the <see cref='System.Management.ManagementEventWatcher'/> class that listens for
/// events conforming to the given WMI event query, according to the specified options. For
/// this variant, the query and the scope are specified as strings. The options
/// object can specify options such as a timeout and context information.</para>
/// </summary>
/// <param name='scope'>The management scope (namespace) in which the watcher will listen for events.</param>
/// <param name=' query'>The query that defines the events for which the watcher will listen.</param>
/// <param name='options'>An <see cref='System.Management.EventWatcherOptions'/> object representing additional options used to watch for events. </param>
public ManagementEventWatcher(
string scope,
string query,
EventWatcherOptions options) : this(new ManagementScope(scope), new EventQuery(query), options) { }
/// <summary>
/// <para> Initializes a new instance of the <see cref='System.Management.ManagementEventWatcher'/> class
/// that listens for events conforming to the given WMI event query, according to the specified
/// options. For this variant, the query and the scope are specified objects. The
/// options object can specify options such as timeout and context information.</para>
/// </summary>
/// <param name='scope'>A <see cref='System.Management.ManagementScope'/> object representing the scope (namespace) in which the watcher will listen for events.</param>
/// <param name=' query'>An <see cref='System.Management.EventQuery'/> object representing a WMI event query, which determines the events for which the watcher will listen.</param>
/// <param name='options'>An <see cref='System.Management.EventWatcherOptions'/> object representing additional options used to watch for events. </param>
public ManagementEventWatcher(
ManagementScope scope,
EventQuery query,
EventWatcherOptions options)
{
if (null != scope)
this.scope = ManagementScope._Clone(scope, new IdentifierChangedEventHandler(HandleIdentifierChange));
else
this.scope = ManagementScope._Clone(null, new IdentifierChangedEventHandler(HandleIdentifierChange));
if (null != query)
this.query = (EventQuery)query.Clone();
else
this.query = new EventQuery();
this.query.IdentifierChanged += new IdentifierChangedEventHandler(HandleIdentifierChange);
if (null != options)
this.options = (EventWatcherOptions)options.Clone();
else
this.options = new EventWatcherOptions();
this.options.IdentifierChanged += new IdentifierChangedEventHandler(HandleIdentifierChange);
enumWbem = null;
cachedCount = 0;
cacheIndex = 0;
sink = null;
delegateInvoker = new WmiDelegateInvoker(this);
}
/// <summary>
/// <para>Ensures that outstanding calls are cleared. This is the destructor for the object.</para>
/// </summary>
~ManagementEventWatcher()
{
// Ensure any outstanding calls are cleared
Stop();
if (null != scope)
scope.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange);
if (null != options)
options.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange);
if (null != query)
query.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange);
}
//
// Events
//
/// <summary>
/// <para> Occurs when a new event arrives.</para>
/// </summary>
public event EventArrivedEventHandler EventArrived;
/// <summary>
/// <para> Occurs when a subscription is canceled.</para>
/// </summary>
public event StoppedEventHandler Stopped;
//
//Public Properties
//
/// <summary>
/// <para>Gets or sets the scope in which to watch for events (namespace or scope).</para>
/// </summary>
/// <value>
/// <para> The scope in which to watch for events (namespace or scope).</para>
/// </value>
public ManagementScope Scope
{
get
{
return scope;
}
set
{
if (null != value)
{
ManagementScope oldScope = scope;
scope = (ManagementScope)value.Clone();
// Unregister ourselves from the previous scope object
if (null != oldScope)
oldScope.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange);
//register for change events in this object
scope.IdentifierChanged += new IdentifierChangedEventHandler(HandleIdentifierChange);
//the scope property has changed so act like we fired the event
HandleIdentifierChange(this, null);
}
else
throw new ArgumentNullException(nameof(value));
}
}
/// <summary>
/// <para>Gets or sets the criteria to apply to events.</para>
/// </summary>
/// <value>
/// <para> The criteria to apply to the events, which is equal to the event query.</para>
/// </value>
public EventQuery Query
{
get
{
return query;
}
set
{
if (null != value)
{
ManagementQuery oldQuery = query;
query = (EventQuery)value.Clone();
// Unregister ourselves from the previous query object
if (null != oldQuery)
oldQuery.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange);
//register for change events in this object
query.IdentifierChanged += new IdentifierChangedEventHandler(HandleIdentifierChange);
//the query property has changed so act like we fired the event
HandleIdentifierChange(this, null);
}
else
throw new ArgumentNullException(nameof(value));
}
}
/// <summary>
/// <para>Gets or sets the options used to watch for events.</para>
/// </summary>
/// <value>
/// <para>The options used to watch for events.</para>
/// </value>
public EventWatcherOptions Options
{
get
{
return options;
}
set
{
if (null != value)
{
EventWatcherOptions oldOptions = options;
options = (EventWatcherOptions)value.Clone();
// Unregister ourselves from the previous scope object
if (null != oldOptions)
oldOptions.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange);
cachedObjects = new IWbemClassObjectFreeThreaded[options.BlockSize];
//register for change events in this object
options.IdentifierChanged += new IdentifierChangedEventHandler(HandleIdentifierChange);
//the options property has changed so act like we fired the event
HandleIdentifierChange(this, null);
}
else
throw new ArgumentNullException(nameof(value));
}
}
/// <summary>
/// <para>Waits for the next event that matches the specified query to arrive, and
/// then returns it.</para>
/// </summary>
/// <returns>
/// <para>A <see cref='System.Management.ManagementBaseObject'/> representing the
/// newly arrived event.</para>
/// </returns>
/// <remarks>
/// <para>If the event watcher object contains options with
/// a specified timeout, the API will wait for the next event only for the specified
/// amount of time; otherwise, the API will be blocked until the next event occurs.</para>
/// </remarks>
public ManagementBaseObject WaitForNextEvent()
{
ManagementBaseObject obj = null;
Initialize();
lock (this)
{
SecurityHandler securityHandler = Scope.GetSecurityHandler();
int status = (int)ManagementStatus.NoError;
try
{
if (null == enumWbem) //don't have an enumerator yet - get it
{
//Execute the query
status = scope.GetSecuredIWbemServicesHandler(Scope.GetIWbemServices()).ExecNotificationQuery_(
query.QueryLanguage,
query.QueryString,
options.Flags,
options.GetContext(),
ref enumWbem);
}
if (status >= 0)
{
if ((cachedCount - cacheIndex) == 0) //cache is empty - need to get more objects
{
//Because Interop doesn't support custom marshalling for arrays, we have to use
//the "DoNotMarshal" objects in the interop and then convert to the "FreeThreaded"
//counterparts afterwards.
IWbemClassObject_DoNotMarshal[] tempArray = new IWbemClassObject_DoNotMarshal[options.BlockSize];
int timeout = (ManagementOptions.InfiniteTimeout == options.Timeout)
? (int)tag_WBEM_TIMEOUT_TYPE.WBEM_INFINITE :
(int)options.Timeout.TotalMilliseconds;
status = scope.GetSecuredIEnumWbemClassObjectHandler(enumWbem).Next_(timeout, (uint)options.BlockSize, tempArray, ref cachedCount);
cacheIndex = 0;
if (status >= 0)
{
//Convert results and put them in cache. Note that we may have timed out
//in which case we might not have all the objects. If no object can be returned
//we throw a timeout exception.
if (cachedCount == 0)
ManagementException.ThrowWithExtendedInfo(ManagementStatus.Timedout);
for (int i = 0; i < cachedCount; i++)
cachedObjects[i] = new IWbemClassObjectFreeThreaded(Marshal.GetIUnknownForObject(tempArray[i]));
}
}
if (status >= 0)
{
obj = new ManagementBaseObject(cachedObjects[cacheIndex]);
cacheIndex++;
}
}
}
finally
{
securityHandler.Reset();
}
if (status < 0)
{
if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else
Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
}
}
return obj;
}
//********************************************
//Start
//********************************************
/// <summary>
/// <para>Subscribes to events with the given query and delivers
/// them, asynchronously, through the <see cref='System.Management.ManagementEventWatcher.EventArrived'/> event.</para>
/// </summary>
public void Start()
{
Initialize();
// Cancel any current event query
Stop();
// Submit a new query
SecurityHandler securityHandler = Scope.GetSecurityHandler();
IWbemServices wbemServices = scope.GetIWbemServices();
try
{
sink = new SinkForEventQuery(this, options.Context, wbemServices);
if (sink.Status < 0)
{
Marshal.ThrowExceptionForHR(sink.Status, WmiNetUtilsHelper.GetErrorInfo_f());
}
// For async event queries we should ensure 0 flags as this is
// the only legal value
int status = scope.GetSecuredIWbemServicesHandler(wbemServices).ExecNotificationQueryAsync_(
query.QueryLanguage,
query.QueryString,
0,
options.GetContext(),
sink.Stub);
if (status < 0)
{
if (sink != null)
{
sink.ReleaseStub();
sink = null;
}
if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else
Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
}
}
finally
{
securityHandler.Reset();
}
}
//********************************************
//Stop
//********************************************
/// <summary>
/// <para>Cancels the subscription whether it is synchronous or asynchronous.</para>
/// </summary>
public void Stop()
{
//For semi-synchronous, release the WMI enumerator to cancel the subscription
if (null != enumWbem)
{
Marshal.ReleaseComObject(enumWbem);
enumWbem = null;
FireStopped(new StoppedEventArgs(options.Context, (int)ManagementStatus.OperationCanceled));
}
// In async mode cancel the call to the sink - this will
// unwind the operation and cause a Stopped message
if (null != sink)
{
sink.Cancel();
sink = null;
}
}
private void Initialize()
{
//If the query is not set yet we can't do it
if (null == query)
throw new InvalidOperationException();
if (null == options)
Options = new EventWatcherOptions();
//If we're not connected yet, this is the time to do it...
lock (this)
{
if (null == scope)
Scope = new ManagementScope();
if (null == cachedObjects)
cachedObjects = new IWbemClassObjectFreeThreaded[options.BlockSize];
}
lock (scope)
{
scope.Initialize();
}
}
internal void FireStopped(StoppedEventArgs args)
{
try
{
delegateInvoker.FireEventToDelegates(Stopped, args);
}
catch
{
}
}
internal void FireEventArrived(EventArrivedEventArgs args)
{
try
{
delegateInvoker.FireEventToDelegates(EventArrived, args);
}
catch
{
}
}
}
internal sealed class SinkForEventQuery : IWmiEventSource
{
private readonly ManagementEventWatcher eventWatcher;
private readonly object context;
private readonly IWbemServices services;
private IWbemObjectSink stub; // The secured IWbemObjectSink
private int status;
private readonly bool isLocal;
public int Status { get { return status; } set { status = value; } }
public SinkForEventQuery(ManagementEventWatcher eventWatcher,
object context,
IWbemServices services)
{
this.services = services;
this.context = context;
this.eventWatcher = eventWatcher;
this.status = 0;
this.isLocal = false;
// determine if the server is local, and if so don't create a real stub using unsecap
if ((string.Equals(eventWatcher.Scope.Path.Server, ".", StringComparison.OrdinalIgnoreCase)) ||
(string.Equals(eventWatcher.Scope.Path.Server, System.Environment.MachineName, StringComparison.OrdinalIgnoreCase)))
{
this.isLocal = true;
}
if (MTAHelper.IsNoContextMTA())
HackToCreateStubInMTA(this);
else
{
//
// Ensure we are able to trap exceptions from worker thread.
//
ThreadDispatch disp = new ThreadDispatch(new ThreadDispatch.ThreadWorkerMethodWithParam(HackToCreateStubInMTA));
disp.Parameter = this;
disp.Start();
}
}
private void HackToCreateStubInMTA(object param)
{
SinkForEventQuery obj = (SinkForEventQuery)param;
object dmuxStub = null;
obj.Status = WmiNetUtilsHelper.GetDemultiplexedStub_f(obj, obj.isLocal, out dmuxStub);
obj.stub = (IWbemObjectSink)dmuxStub;
}
internal IWbemObjectSink Stub
{
get { return stub; }
}
public void Indicate(IntPtr pWbemClassObject)
{
Marshal.AddRef(pWbemClassObject);
IWbemClassObjectFreeThreaded obj = new IWbemClassObjectFreeThreaded(pWbemClassObject);
try
{
EventArrivedEventArgs args = new EventArrivedEventArgs(context, new ManagementBaseObject(obj));
eventWatcher.FireEventArrived(args);
}
catch
{
}
}
public void SetStatus(
int flags,
int hResult,
string message,
IntPtr pErrObj)
{
try
{
// Fire Stopped event
eventWatcher.FireStopped(new StoppedEventArgs(context, hResult));
//This handles cases in which WMI calls SetStatus to indicate a problem, for example
//a queue overflow due to slow client processing.
//Currently we just cancel the subscription in this case.
if (hResult != (int)tag_WBEMSTATUS.WBEM_E_CALL_CANCELLED
&& hResult != (int)tag_WBEMSTATUS.WBEM_S_OPERATION_CANCELLED)
ThreadPool.QueueUserWorkItem(new WaitCallback(Cancel2));
}
catch
{
}
}
// On Win2k, we get a deadlock if we do a Cancel within a SetStatus
// Instead of calling it from SetStatus, we use ThreadPool.QueueUserWorkItem
private void Cancel2(object o)
{
//
// Try catch the call to cancel. In this case the cancel is being done without the client
// knowing about it so catching all exceptions is not a bad thing to do. If a client calls
// Stop (which calls Cancel), they will still receive any exceptions that may have occurred.
//
try
{
Cancel();
}
catch
{
}
}
internal void Cancel()
{
if (null != stub)
{
lock (this)
{
if (null != stub)
{
int status = services.CancelAsyncCall_(stub);
// Release prior to throwing an exception.
ReleaseStub();
if (status < 0)
{
if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else
Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
}
}
}
}
}
internal void ReleaseStub()
{
if (null != stub)
{
lock (this)
{
/*
* We force a release of the stub here so as to allow
* unsecapp.exe to die as soon as possible.
* however if it is local, unsecap won't be started
*/
if (null != stub)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(stub);
stub = null;
}
catch
{
}
}
}
}
}
}
}