Exemplo n.º 1
0
        private void OnManagementEventArrived(object sender, EventArrivedEventArgs e)
        {
            var managementBaseObject = e.NewEvent;

            if (managementBaseObject == null)
            {
                Logger.GetInstance(typeof(WmiProcessWatcher)).Warn("Can not find arrived management event");
                return;
            }

            try
            {
                EventHandler eventHandler = null;
                var          eventType    = managementBaseObject.ClassPath.ClassName;
                foreach (var wmiInstanceEvent in WmiInstanceEvents)
                {
                    if (wmiInstanceEvent.Value.Equals(eventType))
                    {
                        eventHandler = EventHandlers[wmiInstanceEvent.Key];
                    }
                }

                if (eventHandler == null)
                {
                    return;
                }

                var targetInstance = managementBaseObject["TargetInstance"] as ManagementBaseObject;
                if (targetInstance == null)
                {
                    Logger.GetInstance(typeof(WmiProcessWatcher)).Warn("Can not find arrived target instance");
                    return;
                }

                ProcessInfo processInfo = null;
                try
                {
                    var id   = (int)(targetInstance["ProcessId"] as uint? ?? 0);
                    var name = targetInstance["Name"] as string;
                    var path = targetInstance["ExecutablePath"] as string;
                    if (string.IsNullOrWhiteSpace(path))
                    {
                        path = ProcessManager.GetProcessPathById(id);
                    }

                    processInfo = new ProcessInfo
                    {
                        Id   = id,
                        Name = name,
                        Path = path
                    };
                }
                catch (Exception exception)
                {
                    Logger.GetInstance(typeof(WmiProcessWatcher)).Error("Can not process arrived target instance: " + exception.Message);
                }
                finally
                {
                    /*
                     * https://stackoverflow.com/questions/11896282/using-clause-fails-to-call-dispose
                     */
                    targetInstance.Dispose();
                }

                eventHandler(processInfo);
            }
            catch (Exception exception)
            {
                Logger.GetInstance(typeof(WmiProcessWatcher)).Error("Can not process arrived management event: " + exception.Message);
            }
            finally
            {
                /*
                 * https://stackoverflow.com/questions/11896282/using-clause-fails-to-call-dispose
                 */
                managementBaseObject.Dispose();
            }
        }