我在使用多線程時遇到此錯誤。我是新來的,在我的windows應用程序中這個代碼工作。但是我將它傳遞給我收到的Windows服務「線程正在運行或終止,無法重新啓動。」在Windows服務中創建它時,我使用System.Timers.Timer而不是System.Windows.Forms.Timer。這個Windows服務將從數據庫中導出一些XML文件,所以我需要一個計時器。因此,有時會檢查數據庫中是否有新產品或客戶讀取下面的功能。默認情況下,我將時間硬編碼爲1分鐘進行測試。另外,如果函數還沒有完成,我已經創建了一個布爾變量。它不會覆蓋。VB.NET:線程正在運行或終止;它無法重新啓動
這裏是我的代碼:
Dim oIsproc_BP As Boolean
Dim oIsproc_ItemMaster1 As Boolean
Dim thrd As Thread
Protected Overrides Sub onstart(ByVal args() As String)
tmr.Interval = 1000
AddHandler tmr.Elapsed, AddressOf tmr_Elapsed
tmr.Start()
End Sub
Private Sub tmr_Elapsed(sender As Object, e As Timers.ElapsedEventArgs) Handles tmr.Elapsed
oIsproc_BP = False
oIsproc_ItemMaster1 = False
tSecItemMaster.Interval = 60000'oInterval(0)
AddHandler tSecItemMaster.Elapsed, AddressOf tSecItemMaster_Elapsed
tSecItemMaster.Start()
tSecCustomer.Interval = 60000'oInterval(2)
AddHandler tSecCustomer.Elapsed, AddressOf tSecCustomer_Elapsed
tSecCustomer.Start()
tmr.Stop()
End Sub
Private Sub tSecItemMaster_Elapsed(sender As Object, e As Timers.ElapsedEventArgs) Handles tSecItemMaster.Elapsed
If Not oIsproc_ItemMaster1 Then
oIsproc_ItemMaster1 = True
thrd = New Thread(DirectCast(Function() oItemMaster(), ThreadStart))
thrd.Start()
End If
Return
End Sub
Private Sub tSecCustomer_Elapsed(sender As Object, e As Timers.ElapsedEventArgs) Handles tSecCustomer.Elapsed
If Not oIsproc_BP Then
oIsproc_BP = True
thrd = New Thread(DirectCast(Sub() oBPartners(, "C"), ThreadStart))
thrd.Start()
End If
Return
End Sub
而對於我的功能:
Private Function oItemMaster(Optional ByVal FirstLoad As Boolean = False, Optional oType As Integer = 1)
''My code here
oIsproc_ItemMaster1 = False
End Function
Private Sub oBPartners(Optional ByVal FirstLoad As Boolean = False, Optional CardType As String = "C")
''My code here
oIsproc_BP = False
End Function