如何获取进程的线程并将其显示在列表中

时间:2019-09-19 13:20:26

标签: .net vb.net

因此,在VB.NET中,我想获取与进程关联的所有线程,所以我有一个文本框,在其中输入进程名称,然后单击按钮以在与之相关的列表中获取与之关联的所有线程。在表格上。谢谢

我曾尝试对其进行更改,并尝试在Internet上进行搜索,但没有解决方案。

Imports System.Diagnostics
Imports System.Threading
Imports System.Windows.Forms
Imports System.ComponentModel

Public Class Form1

    Private Sub ListThreads()
        Try
            Dim TheProcess As Process() = Process.GetProcessesByName(txtprocessName.Text)
            MessageBox.Show(txtprocessName.Text)

            Dim CurrentProcess As Process = Process.GetCurrentProcess()
            Dim myThreads As ProcessThreadCollection = CurrentProcess.Threads
            Dim thread As Process
            threadList.BeginUpdate()
            threadList.Clear()
            'threadList.Columns.Add("Name", 100, HorizontalAlignment.Left)
            threadList.Columns.Add("ID", 60, HorizontalAlignment.Left)
            threadList.Columns.Add("Priority", 60, HorizontalAlignment.Right)
            threadList.Columns.Add("Start Time", 100, HorizontalAlignment.Right)
            For Each thread In myThreads
                Dim lvi As ListViewItem = New ListViewItem()
                'lvi.Text = thread.ProcessName
                lvi.SubItems.Add(thread.Id)
                lvi.SubItems.Add(thread.BasePriority)
                lvi.SubItems.Add(thread.StartTime)
                threadList.Items.Add(lvi)
            Next thread
            threadList.EndUpdate()
        Catch e As Exception
            MessageBox.Show(e.Message)
        End Try

    End Sub

    Private Sub btnShow_Click(sender As Object, e As EventArgs) Handles btnShow.Click
        ListThreads()
    End Sub
End Class

每次运行它都会显示一个错误 Unable to cast object of type System.Diagnostics.ProcessThread to type System.Diagnostics.Process

我想获取与进程关联的线程并将其显示在列表中。谢谢

1 个答案:

答案 0 :(得分:1)

主要问题是因为thread的类型为Process,但是您返回的是ProcessThread的集合(Dim myThreads As ProcessThreadCollection = CurrentProcess.Threads),它们是不同的

要解决此问题,您可以选择以下几种方法:

  1. thread的类型更改为ProcessThread。例如:Dim thread As ProcessThread(这将纠正实际错误)。
  2. 完全删除变量thread并更改循环;你应该做这个。例如:

    For Each thread As ThreadProcess In myThreads