小弟现在遇到一个问题,希望能借助多线程,隔一段时间就清空数据显示,但是当重复调用Thread.Start(),就会遇到
“A first chance exception of type 'System.Threading.ThreadStateException' occurred in mscorlib.dll”提示的错误是:线程正在运行或被终止;它无法重新启动。
为了方便大家明白我的问题,我编了个简化的版本
窗体上有一个button和timer控件
以下是窗体的代码
VB.NET code
Imports System.Threading
Public Class Form1
Private ThreadCleanData As System.Threading.Thread
Private Declare Function timeGetTime Lib "winmm.dll" Alias "timeGetTime" () As Long
Private LockedObj As New Object
Public ISI As Long = 15 '发送信号15毫秒后,清除寄存器
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
ThreadCleanData = New System.Threading.Thread(AddressOf CleanDataRoutine)
ThreadCleanData.Priority = Threading.ThreadPriority.AboveNormal
With Timer1
.Interval = 2000 '2000毫秒调用一次
.Enabled = False
End With
With Button1
.Text = "Start"
End With
End Sub
Private Sub CleanDataRoutine()
Dim tmStart As Long = timeGetTime
SyncLock LockedObj
While timeGetTime - tmStart < ISI
End While
ClearData()
End SyncLock
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
SendData(Rnd() * 1000)
ThreadCleanData.Start() '这句话是程序出错的位置
End Sub
Private Sub SendData(ByVal Data As Integer)
Debug.Print(Data) '打印
End Sub
Private Sub ClearData()
Debug.Print(0) '清空
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Timer1.Enabled = True
End Sub
End Class
你试一下在线程内循环,不用timer,改用sleep()
Private Sub CleanDataRoutine()
while 1
sleep(15)
ClearData()
end while
End Sub
如果改成这样成不?