首页 > 解决方案 > 如何获取进程的线程并将其显示在列表中

问题描述

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

我试图改变它并尝试在互联网上搜索它,但没有得到解决方案。

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

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

标签: .netvb.net

解决方案


主要问题是因为类型threadProcess,但您返回的是ProcessThread's ( Dim myThreads As ProcessThreadCollection = CurrentProcess.Threads) 的集合,它们不一样。

要解决此问题,您有几个选择:

  1. 将类型更改threadProcessThread。例如:(Dim thread As ProcessThread这将修复实际错误)。

  2. 完全删除变量thread并更改循环;你应该做这个。例如:

    For Each thread As ThreadProcess In myThreads


推荐阅读