Pasar uno o más parámetros a un thread

1887 vistas

El delegado System.Threading.ThreadStart usado por las funciones de thread no tiene ningún parámetro. Para pasar parámetros a un thread tendremos que crear una clase nueva que contenga los parámetros y el método del thread.



vbnet
  1. Imports System.Threading
  2.  
  3. Public Class ThreadsForm
  4.     Inherits System.Windows.Forms.Form
  5.  
  6.     ' ........
  7.  
  8.     Private _threadCalculs1 As Thread
  9.     Private _endThreadCalculsEvent As New ManualResetEvent(False)
  10.  
  11.     ' Clase ThreadCalculs
  12.     Private Class ThreadCalculs
  13.  
  14.         ' form parent
  15.         Private _frm As ThreadsForm
  16.         ' temporizador
  17.         Private _tempo As Integer
  18.  
  19.         ' Constructor. frm y tempo son parámetros del Thread
  20.         Public Sub New(ByVal frm As ThreadsForm, ByVal tempo As Integer)
  21.             _frm = frm
  22.             _tempo = tempo
  23.         End Sub
  24.  
  25.         ' función del Thread
  26.         Public Sub ThrFunc()
  27.             Try
  28.                 _frm.Calculs(_tempo)
  29.             Catch ex As Exception
  30.                 Debug.WriteLine(ex.ToString())
  31.             End Try
  32.         End Sub
  33.     End Class
  34.  
  35.     ' cálculos
  36.     Private Sub Calculs(ByVal tempo As Integer)
  37.         While Not _endThreadCalculsEvent.WaitOne(tempo, False)
  38.             ' aquà hacemos los cálculos.....
  39.         End While
  40.     End Sub
  41.  
  42.     ' arrancamos thread
  43.     Private Sub StartThread()
  44.         Dim myThreadObj As New ThreadCalculs(Me, 1000)
  45.         _threadCalculs1 = New Thread(AddressOf myThreadObj.ThrFunc)
  46.         _threadCalculs1.Name = "Thread1"
  47.         _threadCalculs1.Start()
  48.  
  49.     End Sub