Public Class ThreadSincronizzatore
#Region "VARIABILI INTERNE"
'gestione loop del thread
Private LoopThread As Boolean = False
'thread di sistema
Private ThreadInterno As System.Threading.Thread = Nothing
#End Region
#Region "VARIABILI ESPOSTE DAL THREAD"
'espongo stato del thread
Public ThreadInEsecuzione As Boolean = False
'espongo eventuali errori
Public Errore As String = ""
'EVENTUALE PERCORSO DELLA CARTELLA DA MANIPOLARE
Public PercorsoCartella as string = "C:\PROVA"
#End Region
#Region "GESTIONE START/STOP DEL THREAD"
Public Sub StartThread()
Try
'setto a true il loop infinito del thread
LoopContinuo = True
'creo il thread
ThreadInterno = New System.Threading.Thread(AddressOf CorpoThread)
'avvio il thread
ThreadInterno.Start()
Catch ex As Exception
Errore = "ERR.0000 : Errore durante l'avvio del thread : " + ex.ToString
End Try
End Sub
Public Sub StopThread()
Try
'setto a false il loop continuo del thread
LoopContinuo = False
'memorizzo istante richiesta stop del thread
Dim Istante As Date = Now
'attendo che il thread sia stato effettivamente terminato
Do
'controllo timeout attesa stop thread
If Now.Subtract(Istante).TotalSeconds >= 5 Then
Errore = "Timeout stop thread"
Exit Do
End If
'pausa per permettere agli altri thread di lavorare
Threading.Thread.Sleep(1)
Loop While ThreadInEsecuzione = True
'una volta terminato il thread libero le risorse
ThreadInterno.Abort()
Catch ex As Exception
End Try
End Sub
#End Region
#Region "CORPO DEL THREAD"
Private Sub CorpoThread()
Do
'segnalo thread in esecuzione
ThreadInEsecuzione = True
'INSERISCI QUI TUTTO QUELLO CHE VUOI FARE
'pausa per permettere agli altri thread di lavorare
Threading.Thread.Sleep(10)
Loop While LoopThread = True
'segnalo thread terminato
ThreadInEsecuzione = False
End Sub
#End Region
End Class