我的代码中有 VB.Net 后台工作者吗?

发布于 2024-12-08 05:30:45 字数 10463 浏览 1 评论 0原文

我对 vb.net 有点菜鸟,我制作了这个应用程序来执行大量的 http 请求和流读取。但当它这样做时,它总是冻结我的应用程序。

所以我做了一些研究,发现我可以使用后台工作者来解决这个问题。但我不知道从哪里开始。因此,如果您可以查看我的代码并告诉我在哪里以及如何添加后台工作人员以防止冻结,那就太棒了。

Imports mshtml
Imports System.Net
Imports System.Threading
Imports System.Text
Imports System.IO
Imports System.Web

Public Class Form1
    Inherits Form

    Private Delegate Sub MyDelegate(show As Boolean)
    Private demoThread As System.Threading.Thread = Nothing
    Private demoThread2 As System.Threading.Thread = Nothing

    Private Sub ShowProgressOnThread()
        Dim newProgressWindow As New Form2
        newProgressWindow.Show()
    End Sub

    Public Function GetTableText(ByVal sHTML As String) As String
       Dim myDoc As mshtml.IHTMLDocument2 = New mshtml.HTMLDocument
        Dim mElement As mshtml.IHTMLElement
        Dim mElement2 As mshtml.IHTMLElement
        Dim mECol As mshtml.IHTMLElementCollection

        'initialize the document object within the HTMLDocument class...
        myDoc.close()
        myDoc.open("about:blank")
        'write the HTML to the document using the MSHTML "write" method...

        Dim clsHTML() As Object = {sHTML}
        myDoc.write(clsHTML)
        clsHTML = Nothing
        mElement = myDoc.body()
        mECol = mElement.getElementsByTagName("TD")

        Dim gData As ListViewItem

        For A = 3 To mECol.length - 1 Step +6

            mElement2 = mECol.item(A)

            gData = Me.ListView1.Items.Add(mElement2.innerText)

            mElement2 = mECol.item(A - 1)

            gData.SubItems.Add(mElement2.innerText.ToUpper)

            'Frm.Close()



            ' lstResults.Items.Add("Game : " & mElement2.innerText)
        Next
    End Function

    Private Sub wait(ByVal interval As Integer)
        Dim sw As New Stopwatch
        sw.Start()
        Do While sw.ElapsedMilliseconds < interval
            ' Allows UI to remain responsive
            Application.DoEvents()
        Loop
        sw.Stop()
    End Sub

    Private Sub Button__()
        Me.ResetText()
        Me.ToolStripStatusLabel1.Text = "Loading..."
        Me.Text = "Game Finder | By Unh0ly | Loading..."
        ' Me.demoThread = New Thread( _
        'New ThreadStart(AddressOf Me.Loader))

        ' Me.demoThread.Start()

        'Me.Invoke(New MethodInvoker(AddressOf Me.Loader))



        'Me.Frm.Show()
        'Application.Run(Frm)


        Dim srchText As String
        srchText = TextBox1.Text.Replace(" ", "%20")

        Dim request As HttpWebRequest = HttpWebRequest.Create("****" & srchText)
        'Dim response As HttpWebResponse

        Dim response As HttpWebResponse = request.GetResponse()

        Dim sr As System.IO.StreamReader = New System.IO.StreamReader(response.GetResponseStream())

        Dim sourcecode As String = sr.ReadToEnd()


        If sourcecode.Contains("<td>") Then
            GetTableText(sourcecode)

            Me.ResetText()
            Me.Text = "Game Finder | By Unh0ly"
            Me.ToolStripStatusLabel1.Text = "Done"
            Call wait(2500)
            Me.ToolStripStatusLabel1.Text = "Status.."
            'newProgressWindow.Hide()
            'newProgressWindow.Dispose()
            'Form2.Refresh()
        ElseIf Not sourcecode.Contains("<td>") Then
            ' newProgressWindow.Hide()
            ' Progress.Dispose()
            MessageBox.Show("No Results Found For: " + TextBox1.Text)
        End If
        'Dim sHTML = sourcecode
        'For I = 2 To mECol.length - 1 Step +6


    End Sub

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click

        'Frm.Show()

        Me.Invoke(New MethodInvoker(AddressOf Button__))

        'Dim demoThread As System.Threading.Thread
    End Sub

    Private Sub CopyToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles CopyToolStripMenuItem.Click, IDAndGameNameToolStripMenuItem.Click
        Try

            Dim s As String


            Dim lsvrow
            lsvrow = ListView1.SelectedItems(0)

            s = "Game Name: " + lsvrow.Text + ControlChars.NewLine + "ID: " + TextBox2.Text



            Clipboard.SetDataObject(s)
        Catch ex As System.Exception
            MessageBox.Show("Error: " + ex.Message)
        Finally
            ' Perform any tidy up code.
        End Try
    End Sub
    Private Sub CopyIDToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles CopyIDToolStripMenuItem.Click, IDToolStripMenuItem.Click
        Try
            Dim s As String


            Dim lsvrow
            lsvrow = ListView1.SelectedItems(0)

            s = TextBox2.Text



            Clipboard.SetDataObject(s)

        Catch ex As System.Exception
            MessageBox.Show("Error: " + ex.Message)
        Finally
            ' Perform any tidy up code.
        End Try
    End Sub


    Private Sub ListView1_ItemActivate(sender As System.Object, e As System.Windows.Forms.ListViewItemSelectionChangedEventArgs) Handles ListView1.ItemSelectionChanged

        TextBox2.Text = e.Item.SubItems(1).Text
    End Sub

    Private Sub TextBox1_KeyDown(sender As System.Object, e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown
        If e.KeyCode = Keys.Enter Then
            'Runs the Button1_Click Event
            Button1_Click(Me, EventArgs.Empty)
        End If
    End Sub

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load

    End Sub



    Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click, ClearToolStripMenuItem.Click
        ListView1.Items.Clear()
    End Sub

    Private Sub DownloadGPDToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles DownloadGPDToolStripMenuItem.Click, DownloadGPDToolStripMenuItem1.Click

        Dim gpds As ArrayList = New ArrayList()

        Const YOUR_DIRECTORY As String = "****"

        ' Get the object used to communicate with the server.
        Dim request As FtpWebRequest = CType(WebRequest.Create(YOUR_DIRECTORY), FtpWebRequest)
        request.Method = WebRequestMethods.Ftp.ListDirectoryDetails
        ' This example assumes the FTP site uses anonymous logon.
        request.Credentials = New NetworkCredential("****", "****")

        Call wait(1500)

        Dim response As FtpWebResponse = CType(request.GetResponse, FtpWebResponse)
        Dim responseStream As Stream = response.GetResponseStream
        Dim reader As StreamReader = New StreamReader(responseStream)
        Dim s = reader.ReadToEnd

        reader.Close()
        response.Close()

        If Len(TextBox2.Text) > 0 Then
            If s.Contains(TextBox2.Text + ".gpd") Then
                FolderBrowserDialog1.ShowDialog()

                If Not FolderBrowserDialog1.SelectedPath = Nothing Then

                    Me.Text = "Game Finder | By Unh0ly | Downloading..."
                    Me.ToolStripStatusLabel1.Text = "Downloading..."
                    My.Computer.Network.DownloadFile("****" + TextBox2.Text + ".gpd", FolderBrowserDialog1.SelectedPath + "\" + TextBox2.Text + ".gpd", "", "", False, "100", True)
                    Me.ResetText()
                    Me.ToolStripStatusLabel1.Text = "Status.."
                ElseIf FolderBrowserDialog1.SelectedPath = Nothing Then

                Else
                    MessageBox.Show("No GPD for Selected Game")
                End If
            Else
                MessageBox.Show("No GPD for Selected Game")
            End If
        Else
            ' Do Nothing
        End If
    End Sub

    Private Sub ExitToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles ExitToolStripMenuItem.Click
        Application.Exit()
    End Sub

    Private Sub CheckForUpdatesToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles CheckForUpdatesToolStripMenuItem.Click
        Dim request As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create("****")
        Dim response As System.Net.HttpWebResponse = request.GetResponse()

        Dim sr As System.IO.StreamReader = New System.IO.StreamReader(response.GetResponseStream())

        Dim newestversion As String = sr.ReadToEnd()
        Dim currentversion As String = Application.ProductVersion

        Dim request1 As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create("****")
        Dim response1 As System.Net.HttpWebResponse = request1.GetResponse()

        Dim sr1 As System.IO.StreamReader = New System.IO.StreamReader(response1.GetResponseStream())

        Dim updurl As String = sr1.ReadToEnd()

        If newestversion.Contains(currentversion) Then
            MessageBox.Show("You have the current version", "Up to date", MessageBoxButtons.OK, MessageBoxIcon.Information)
        Else
            Dim result1 As DialogResult = MessageBox.Show("Newer version available" & vbCrLf & "Please Goto *** to check" + vbCrLf + "Do you want to go there now?", "Update Available", MessageBoxButtons.YesNo, MessageBoxIcon.Information)

            If result1 = DialogResult.Yes Then
                Process.Start(updurl)
            Else
                ' Do Nothing
            End If
        End If
    End Sub

    Private Sub AboutToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles AboutToolStripMenuItem.Click
        Dim gpds As ArrayList = New ArrayList()

        Const YOUR_DIRECTORY As String = "****"


        Dim request As FtpWebRequest = CType(WebRequest.Create(YOUR_DIRECTORY), FtpWebRequest)
        request.Method = WebRequestMethods.Ftp.ListDirectoryDetails

        request.Credentials = New NetworkCredential("****", "****")

        Call wait(100)

        Dim response As FtpWebResponse = CType(request.GetResponse, FtpWebResponse)
        Dim responseStream As Stream = response.GetResponseStream
        Dim reader As StreamReader = New StreamReader(responseStream)
        Dim s = reader.ReadToEnd

        reader.Close()
        response.Close()

        Dim Lines() As String = s.Split(New String() {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)

        MessageBox.Show("Made By Unh0ly aka Nickdudego3" & vbCrLf & "Number of GPD's: " & Lines.Length - 5 & vbCrLf & "Version: " & Application.ProductVersion, "About", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
    End Sub
End Class

I am a bit of a noobie with vb.net and I made this application that does a lot of http requests and stream reading. But when it does this it always freezes my application.

So I did a little research and found that I could use background workers to solve this. But I have no idea where to start. So if you could look at my code and tell me where and how I can add background workers to prevent the freezing that would be awesome.

Imports mshtml
Imports System.Net
Imports System.Threading
Imports System.Text
Imports System.IO
Imports System.Web

Public Class Form1
    Inherits Form

    Private Delegate Sub MyDelegate(show As Boolean)
    Private demoThread As System.Threading.Thread = Nothing
    Private demoThread2 As System.Threading.Thread = Nothing

    Private Sub ShowProgressOnThread()
        Dim newProgressWindow As New Form2
        newProgressWindow.Show()
    End Sub

    Public Function GetTableText(ByVal sHTML As String) As String
       Dim myDoc As mshtml.IHTMLDocument2 = New mshtml.HTMLDocument
        Dim mElement As mshtml.IHTMLElement
        Dim mElement2 As mshtml.IHTMLElement
        Dim mECol As mshtml.IHTMLElementCollection

        'initialize the document object within the HTMLDocument class...
        myDoc.close()
        myDoc.open("about:blank")
        'write the HTML to the document using the MSHTML "write" method...

        Dim clsHTML() As Object = {sHTML}
        myDoc.write(clsHTML)
        clsHTML = Nothing
        mElement = myDoc.body()
        mECol = mElement.getElementsByTagName("TD")

        Dim gData As ListViewItem

        For A = 3 To mECol.length - 1 Step +6

            mElement2 = mECol.item(A)

            gData = Me.ListView1.Items.Add(mElement2.innerText)

            mElement2 = mECol.item(A - 1)

            gData.SubItems.Add(mElement2.innerText.ToUpper)

            'Frm.Close()



            ' lstResults.Items.Add("Game : " & mElement2.innerText)
        Next
    End Function

    Private Sub wait(ByVal interval As Integer)
        Dim sw As New Stopwatch
        sw.Start()
        Do While sw.ElapsedMilliseconds < interval
            ' Allows UI to remain responsive
            Application.DoEvents()
        Loop
        sw.Stop()
    End Sub

    Private Sub Button__()
        Me.ResetText()
        Me.ToolStripStatusLabel1.Text = "Loading..."
        Me.Text = "Game Finder | By Unh0ly | Loading..."
        ' Me.demoThread = New Thread( _
        'New ThreadStart(AddressOf Me.Loader))

        ' Me.demoThread.Start()

        'Me.Invoke(New MethodInvoker(AddressOf Me.Loader))



        'Me.Frm.Show()
        'Application.Run(Frm)


        Dim srchText As String
        srchText = TextBox1.Text.Replace(" ", "%20")

        Dim request As HttpWebRequest = HttpWebRequest.Create("****" & srchText)
        'Dim response As HttpWebResponse

        Dim response As HttpWebResponse = request.GetResponse()

        Dim sr As System.IO.StreamReader = New System.IO.StreamReader(response.GetResponseStream())

        Dim sourcecode As String = sr.ReadToEnd()


        If sourcecode.Contains("<td>") Then
            GetTableText(sourcecode)

            Me.ResetText()
            Me.Text = "Game Finder | By Unh0ly"
            Me.ToolStripStatusLabel1.Text = "Done"
            Call wait(2500)
            Me.ToolStripStatusLabel1.Text = "Status.."
            'newProgressWindow.Hide()
            'newProgressWindow.Dispose()
            'Form2.Refresh()
        ElseIf Not sourcecode.Contains("<td>") Then
            ' newProgressWindow.Hide()
            ' Progress.Dispose()
            MessageBox.Show("No Results Found For: " + TextBox1.Text)
        End If
        'Dim sHTML = sourcecode
        'For I = 2 To mECol.length - 1 Step +6


    End Sub

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click

        'Frm.Show()

        Me.Invoke(New MethodInvoker(AddressOf Button__))

        'Dim demoThread As System.Threading.Thread
    End Sub

    Private Sub CopyToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles CopyToolStripMenuItem.Click, IDAndGameNameToolStripMenuItem.Click
        Try

            Dim s As String


            Dim lsvrow
            lsvrow = ListView1.SelectedItems(0)

            s = "Game Name: " + lsvrow.Text + ControlChars.NewLine + "ID: " + TextBox2.Text



            Clipboard.SetDataObject(s)
        Catch ex As System.Exception
            MessageBox.Show("Error: " + ex.Message)
        Finally
            ' Perform any tidy up code.
        End Try
    End Sub
    Private Sub CopyIDToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles CopyIDToolStripMenuItem.Click, IDToolStripMenuItem.Click
        Try
            Dim s As String


            Dim lsvrow
            lsvrow = ListView1.SelectedItems(0)

            s = TextBox2.Text



            Clipboard.SetDataObject(s)

        Catch ex As System.Exception
            MessageBox.Show("Error: " + ex.Message)
        Finally
            ' Perform any tidy up code.
        End Try
    End Sub


    Private Sub ListView1_ItemActivate(sender As System.Object, e As System.Windows.Forms.ListViewItemSelectionChangedEventArgs) Handles ListView1.ItemSelectionChanged

        TextBox2.Text = e.Item.SubItems(1).Text
    End Sub

    Private Sub TextBox1_KeyDown(sender As System.Object, e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown
        If e.KeyCode = Keys.Enter Then
            'Runs the Button1_Click Event
            Button1_Click(Me, EventArgs.Empty)
        End If
    End Sub

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load

    End Sub



    Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click, ClearToolStripMenuItem.Click
        ListView1.Items.Clear()
    End Sub

    Private Sub DownloadGPDToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles DownloadGPDToolStripMenuItem.Click, DownloadGPDToolStripMenuItem1.Click

        Dim gpds As ArrayList = New ArrayList()

        Const YOUR_DIRECTORY As String = "****"

        ' Get the object used to communicate with the server.
        Dim request As FtpWebRequest = CType(WebRequest.Create(YOUR_DIRECTORY), FtpWebRequest)
        request.Method = WebRequestMethods.Ftp.ListDirectoryDetails
        ' This example assumes the FTP site uses anonymous logon.
        request.Credentials = New NetworkCredential("****", "****")

        Call wait(1500)

        Dim response As FtpWebResponse = CType(request.GetResponse, FtpWebResponse)
        Dim responseStream As Stream = response.GetResponseStream
        Dim reader As StreamReader = New StreamReader(responseStream)
        Dim s = reader.ReadToEnd

        reader.Close()
        response.Close()

        If Len(TextBox2.Text) > 0 Then
            If s.Contains(TextBox2.Text + ".gpd") Then
                FolderBrowserDialog1.ShowDialog()

                If Not FolderBrowserDialog1.SelectedPath = Nothing Then

                    Me.Text = "Game Finder | By Unh0ly | Downloading..."
                    Me.ToolStripStatusLabel1.Text = "Downloading..."
                    My.Computer.Network.DownloadFile("****" + TextBox2.Text + ".gpd", FolderBrowserDialog1.SelectedPath + "\" + TextBox2.Text + ".gpd", "", "", False, "100", True)
                    Me.ResetText()
                    Me.ToolStripStatusLabel1.Text = "Status.."
                ElseIf FolderBrowserDialog1.SelectedPath = Nothing Then

                Else
                    MessageBox.Show("No GPD for Selected Game")
                End If
            Else
                MessageBox.Show("No GPD for Selected Game")
            End If
        Else
            ' Do Nothing
        End If
    End Sub

    Private Sub ExitToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles ExitToolStripMenuItem.Click
        Application.Exit()
    End Sub

    Private Sub CheckForUpdatesToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles CheckForUpdatesToolStripMenuItem.Click
        Dim request As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create("****")
        Dim response As System.Net.HttpWebResponse = request.GetResponse()

        Dim sr As System.IO.StreamReader = New System.IO.StreamReader(response.GetResponseStream())

        Dim newestversion As String = sr.ReadToEnd()
        Dim currentversion As String = Application.ProductVersion

        Dim request1 As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create("****")
        Dim response1 As System.Net.HttpWebResponse = request1.GetResponse()

        Dim sr1 As System.IO.StreamReader = New System.IO.StreamReader(response1.GetResponseStream())

        Dim updurl As String = sr1.ReadToEnd()

        If newestversion.Contains(currentversion) Then
            MessageBox.Show("You have the current version", "Up to date", MessageBoxButtons.OK, MessageBoxIcon.Information)
        Else
            Dim result1 As DialogResult = MessageBox.Show("Newer version available" & vbCrLf & "Please Goto *** to check" + vbCrLf + "Do you want to go there now?", "Update Available", MessageBoxButtons.YesNo, MessageBoxIcon.Information)

            If result1 = DialogResult.Yes Then
                Process.Start(updurl)
            Else
                ' Do Nothing
            End If
        End If
    End Sub

    Private Sub AboutToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles AboutToolStripMenuItem.Click
        Dim gpds As ArrayList = New ArrayList()

        Const YOUR_DIRECTORY As String = "****"


        Dim request As FtpWebRequest = CType(WebRequest.Create(YOUR_DIRECTORY), FtpWebRequest)
        request.Method = WebRequestMethods.Ftp.ListDirectoryDetails

        request.Credentials = New NetworkCredential("****", "****")

        Call wait(100)

        Dim response As FtpWebResponse = CType(request.GetResponse, FtpWebResponse)
        Dim responseStream As Stream = response.GetResponseStream
        Dim reader As StreamReader = New StreamReader(responseStream)
        Dim s = reader.ReadToEnd

        reader.Close()
        response.Close()

        Dim Lines() As String = s.Split(New String() {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)

        MessageBox.Show("Made By Unh0ly aka Nickdudego3" & vbCrLf & "Number of GPD's: " & Lines.Length - 5 & vbCrLf & "Version: " & Application.ProductVersion, "About", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
    End Sub
End Class

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

昨迟人 2024-12-15 05:30:45

这是如何使用工人的小示例..

    Friend WithEvents myWorker As System.ComponentModel.BackgroundWorker
    Me.myWorker = New System.ComponentModel.BackgroundWorker()

  Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
     myWorker.RunWorkerAsync()
  End Sub

  Private Sub myWorker_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles myWorker.DoWork
  'do your stuff here...
  End Sub

Here's a small sample how to use a worker..

    Friend WithEvents myWorker As System.ComponentModel.BackgroundWorker
    Me.myWorker = New System.ComponentModel.BackgroundWorker()

  Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
     myWorker.RunWorkerAsync()
  End Sub

  Private Sub myWorker_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles myWorker.DoWork
  'do your stuff here...
  End Sub
满栀 2024-12-15 05:30:45

查找代码中瓶颈的最佳方法是放置 Timer.StartTimer.Stop 围绕你的方法找出哪些方法执行时间最长。

一旦找到有问题的方法,您可以使用 ThreadPool.QueueUserWorkItem 来实现基本的后台线程。线程绝非易事,您需要一些时间才能弄清楚使用线程时发生的所有疯狂和奇怪的事情。

希望这有帮助。如果您还有其他问题,请询问。

The best way to find bottle neck in your code is to put Timer.Start and Timer.Stop around your methods to find out which methods are taking the longest to excute.

Once you find the offending methods, you can use ThreadPool.QueueUserWorkItem to implement a basic background threading. Threading is by no means easy and it would take some time for you figure it out all the crazy and weird things that happen when you play with threads.

Hope this helps. If you have any more question, do ask.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文