避免在vb.net中挂起表单

时间:2013-02-28 04:26:16

标签: vb.net

我想知道你建议在执行存储过程时避免我的表单挂起的方法。请参阅我附带的代码。我通过Stream API从Twitter收集数据,并在执行sproc时表单挂起。 使用BackgroundWorker是避免形式悬挂的最佳方法吗?你能给我一个例子,说明如何在我的代码中实现它。

Imports System.Linq
Imports System.Text
Imports System.Net
Imports System.IO
Imports Newtonsoft.Json.Linq
Imports Newtonsoft.Json
Imports System.Data.SqlClient
Imports System.Threading

Public Class Form1

    Private Sub btnDB_Click(sender As System.Object, e As System.EventArgs) Handles btnDB.Click
        Dim url As String = "https://stream.twitter.com/1.1/statuses/filter.json?track=twitter"
        Dim request As WebRequest = WebRequest.Create(url)
        request.Credentials = New NetworkCredential("username", "pwd")
        Dim WebResponse = request.GetResponse()
        Dim encode As Encoding = Encoding.GetEncoding("utf-8")
        Dim responseStrem = New StreamReader(WebResponse.GetResponseStream(), encode)




        While Not responseStrem.EndOfStream
            'Console.WriteLine(responseStrem.ReadLine());

            Dim json As String = responseStrem.ReadLine()
            If json.Length <> 0 Then
                ParseJson(json)
            End If
        End While
    End Sub

    Private Sub ParseJson(ByVal Json As String)

        Dim connectionstring As String = "Data Source=.;Initial Catalog=db_twitter_stream;User ID=sa;Password=xxx"
        Dim counter As Integer = 0
        Dim conn As New SqlConnection(connectionstring)
        conn.Open()
        Dim o As JObject = JObject.Parse(json)

        Dim tweet As String = o("text")
        Dim source As String = o("source")
        Dim created_at As String = o("created_at")

        Dim cmd As New SqlCommand("dbo.prc_tweets", conn)
        cmd.CommandType = System.Data.CommandType.StoredProcedure
        cmd.Parameters.Add(New SqlParameter("@tweet", tweet))
        cmd.Parameters.Add(New SqlParameter("@source", source))
        cmd.Parameters.Add(New SqlParameter("@created_at", created_at))

        cmd.ExecuteNonQuery()

        counter = counter + 1
        lblCount.Text = counter.ToString()



        conn.Close()

    End Sub

    Private Sub btnQuit_Click(sender As System.Object, e As System.EventArgs) Handles btnQuit.Click
        Me.Close()
    End Sub



End Class

1 个答案:

答案 0 :(得分:0)

您的表单因为您在主线程中运行代码而挂起。主线程负责响应鼠标点击,显示输出和循环以获取输入。但是一旦你让主线程沉溺于其他东西,它就会在执行你的代码时不再运行它的所有任务,这使得它看起来像你的表单被卡住了。您需要为更大的任务创建另一个线程。您需要使用System.Threading类中的线程池或更多过程。创建一个像Private Sub这样的子类并将其命名为并将所有繁忙的代码放入其中并使用End Sub结束sub。然后创建一个线程变量并将其发送到该Sub。 Dim variable As New System.Threading.Thread(AddressOf yoursubnamehere)。然后将其属性设置为优先级等。然后threadvariable.Start()。问题解决了 :) 如果对您来说更方便,也可以使用backgroundworker。