繁体   English   中英

如何在 NetCore 应用程序中使用 Microsoft.Management.Infrastructure 订阅事件?

[英]How to subscribe to events using Microsoft.Management.Infrastructure in a NetCore application?

我想知道如何使用 Microsoft.Management.Infrastructure 库在 NetCore 应用程序中订阅和接收事件。

到目前为止,我可以使用以下方式查询一些数据:

var options = new CimSessionOptions();
var securePassword = new SecureString();
foreach (var c in password)
    securePassword.AppendChar(c);

var credentials = new CimCredential(PasswordAuthenticationMechanism.Default, "", "user", securePassword);
options.AddDestinationCredentials(GetCredentials(user, password));

CimSession session = CimSession.Create(url, options);
var queryInstance = mySession.QueryInstances("a namespace", "WQL", "a query");
foreach (var instance in queryInstance)
    Console.WriteLine(instance.ToString());

在 Internet 上搜索,我看到了使用 System.Management 执行此操作的示例,如下所示:

ManagementEventWatcher watcher = new ManagementEventWatcher("namespace", "query");
watcher.EventArrived += new EventArrivedEventHandler(EventArrived);
watcher.Start();

但不幸的是我不能使用这个 package,我只需要等效但使用 MMI。

我已经看到一些 class 可能可以帮助我完成这项任务,例如CimIndicationWatcher ,它是 Microsoft.Management.Infrastructure.CimCmdlets package 的一部分,但是我将它导入到我的项目中,但我无法访问其中的任何类。

缺少有关使用此 class 或一般情况下的文档/示例。

我找到了一种方法,不确定是否正确,但我能够使用 Microsoft.Management.Infrastructure 库接收事件。

我是这样做的:

/// Create an observer class
class CimInstanceWatcher : IObserver<CimSubscriptionResult>
{
    public void OnCompleted()
    {
        Console.WriteLine("Done");
    }

    public void OnError(Exception e)
    {
        Console.WriteLine("Error: " + e.Message);
    }

    public void OnNext(CimSubscriptionResult value)
    {
        Console.WriteLine("Event received: " + e.Message);
    }
}

现在,以这种方式使用它:

static void Main(string[] args)
{
    CimSession session = CimSession.Create("MY-PC");
    // create a watcher
    var watcher= new CimInstanceWatcher();
    var queryInstance = GetValues(session).Subscribe(watcher);

    // close application once events are no longer required to be received
    Console.ReadLine();
    session.Close();
}

public static CimAsyncMultipleResults<CimSubscriptionResult> GetValues(CimSession _session)
{
    // Subscribe to any event, in this case, fire an event when an application is opened
    return _session.SubscribeAsync(@"root\cimv2", "WQL", "SELECT targetInstance.Name FROM __InstanceCreationEvent within 2 " +
        "WHERE targetinstance isa \"Win32_Process\"");
}

现在将在OnNext方法上注册事件,如果有错误也会提示给观察者。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM