如何在不使用计时器控制的情况下每隔x秒运行一次线程

时间:2014-05-10 00:03:06

标签: vb.net

我必须每秒运行一个某个线程刷新消息字段,但不使用任何时间控件。我想知道是否有替代定时器控制。我是背景工作者或类似的东西。

这是我到目前为止所做的。它假设每秒运行一次,但它没有

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

    Dim myThread As New System.Threading.Thread(AddressOf GetData)
    myThread.Start()
    Thread.Sleep(1000)
End Sub

这是他要求的功能:

Delegate Sub SetTextCallback(ByVal newString As String)

Private Sub SetText(ByVal [text] As String)
    If Me.ChatBox.InvokeRequired Then
        Dim d As New SetTextCallback(AddressOf SetText)
        Me.Invoke(d, New Object() {[text]})
    Else
        Me.ChatBox.Text = [text]
    End If
End Sub​

Sub GetData()
    Try
        conn.Open()
        Dim Query = "SELECT * fROM messages where Time_Posted > Now()"
        Dim cmd As MySqlCommand = New MySqlCommand(Query, conn)
        Dim theREader As MySqlDataReader = cmd.ExecuteReader
        SetText("")
        Dim Temp as String = ""
        Do While theREader.Read()
            Temp &= theREader.GetString(0) & vbCrLf
        Loop
        SetText(Temp)
        conn.Close()
    Catch ex As Exception
        MsgBox(ex.Message.ToString())
        conn.Close()
    End Try
 GetData()
End Sub

我想知道如果不使用计时器,我怎么能让线程重复运行?

提前感谢您提供任何帮助和建议

在解决问题之后,这是正确的修改后的代码

2 个答案:

答案 0 :(得分:1)

然后看看这个

Imports System.Threading
Public Class Form1
    Dim testvalue As Integer
    Private Sub main_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        Dim myThread As New System.Threading.Thread(AddressOf GetData)
        myThread.Start()
        Thread.Sleep(1000)
    End Sub

    Sub GetData()

        MsgBox("getdata works")

        'get your new data from database here
        'threadsleep here if you want

        'and call   GetData() again 

        GetData()


    End Sub
    '
    '
    '

End Class

答案 1 :(得分:-1)

现在我必须在没有任何计时器的情况下进行非停止proc读取。如果需要,可以添加线程睡眠

将其粘贴到新项目

Public Class Form1
    Dim testvalue As Integer
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        testvalue = 1
'now we gotta run our proc first time 
        Read(testvalue)


    End Sub

    Private Sub Read(ByVal msg As String)


        MsgBox(msg)
        testvalue += 1 'you make make threadsleep here if you want
        Read(testvalue) 'after first start we did what we ant , and now we are running it again 

    End Sub

End Class