0

编辑

我仍然无法为进程分配与之关联的会话 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
4

1 回答 1

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参数。


编辑#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)访问用户字典,那么列表将比字典更合适。

于 2012-01-20T21:49:04.037 回答