使用从wmi查询vb.net获取的新字段更新字典中的值

时间:2012-01-20 20:21:57

标签: vb.net dictionary key-value containskey

修改

我仍然无法为进程分配与之关联的会话ID的用户名。

这是我用来检索用户详细信息的代码:

    Public Sub GetUsers()
    Using server As ITerminalServer = manager.GetRemoteServer(strHostName)
        server.Open()
        For Each session As ITerminalServicesSession In server.GetSessions()
            If Not String.IsNullOrEmpty(session.UserName) Then
                dictuser.Add(session.SessionId, New User(session.SessionId, session.UserName))
            End If
        Next
    End Using
End Sub

我的用户类简单定义为:

Public Class User
Private _SessionID As Integer
Private _UserName As String

Sub New(ByVal SessionID As Integer, ByVal UserName As String)
    _SessionID = SessionID
    _UserName = UserName
End Sub

Public ReadOnly Property SessionID As String
    Get
        Return _SessionID
    End Get
End Property

Public ReadOnly Property UserName As String
    Get
        Return _UserName
    End Get
End Property
End Class

我在我的流程类中创建了一个函数:

Public Sub AddUserInfo(ByVal UserName As String)
    _UserName = UserName
End Sub

1 个答案:

答案 0 :(得分:1)

如果在字典中找到具有相同id的进程,则会替换该进程,否则会自动添加新进程。

dictProcess(process.ProcessId) = process

编辑(回复您编辑过的问题):

我会将Processes类的名称更改为Process,因为它不是集合,但应该代表一个进程。您可以将Process类的构造函数更改为

Public Sub New(ByVal ProcessId As Integer, ByVal ProcessName As String, ByVal SessionId As Integer)            
    _ProcessId = ProcessId            
    _ProcessName = ProcessName            
    _SessionId = SessionId            
End Sub

然后添加方法

Public Sub AddWmiInfo (ByVal PageFileUsage As Integer, ByVal WorkingSetSize As Integer)
    _PageFileUsage = PageFileUsage            
    _WorkingSetSize = WorkingSetSize            
End Sub

或者,您也可以将这些属性读/写,但是您可以获得更好的封装。

使用Cassia将基本过程信息添加到字典中。请注意,ProcessId被声明为Integer,因此检查Not String.IsNullOrEmpty(process.ProcessId)毫无意义。

For Each process As ITerminalServicesProcess In server.GetProcesses()                       
    dictprocess.Add( _
      process.ProcessId, _
      New Process(process.ProcessId, process.ProcessName, process.SessionId))                       
Next

最后,您将添加来自WMI的信息,如此

Dim p As Process = Nothing
For Each wmiProcess In prowmi
    If dictprocess.TryGetValue(wmiProcess.ProcessID, p) Then
        p.AddWmiInfo(wmiProcess.PageFileUsage, wmiProcess.WorkingSetSize)
    End If
Next

TryGetValue会在变量p中返回一个进程。 TryGetValue的第二个参数是ByRef参数。


EDIt#2:

你的循环应该是

Dim p As Process = Nothing
For Each user As User In dictuser.Values
    If dictprocess.TryGetValue(user.SessionID, p) Then
        p.AddUserInfo(user.UserName)
    End If
Next

但是,如果您从未通过密钥(会话ID)访问用户词典,那么列表将比字典更合适。