2010-10-25 15 views
10

Sto cercando di passare due o più parametri a un thread in VB 2008.Come passare più parametri in discussione in VB

Il seguente metodo (modificato) funziona bene senza parametri, e la mia barra di stato viene aggiornato molto cool-y. Ma non riesco a farlo funzionare con uno, due o più parametri.

Questa è la pseudo codice di quello che sto pensando dovrebbe accadere quando si preme il pulsante:

Private Sub Btn_Click() 

Dim evaluator As New Thread(AddressOf Me.testthread(goodList, 1)) 
evaluator.Start() 

Exit Sub 

Questo è il metodo testthread:

Private Sub testthread(ByRef goodList As List(Of OneItem), ByVal coolvalue As Integer) 

    StatusProgressBar.Maximum = 100000 
    While (coolvalue < 100000) 
     coolvalue = coolvalue + 1 
     StatusProgressBar.Value = coolvalue 
     lblPercent.Text = coolvalue & "%" 
     Me.StatusProgressBar.Refresh() 
    End While 

End Sub 

risposta

0

basta creare una classe o struttura che ha due membri, uno List(Of OneItem) e l'altro Integer e inviano un'istanza di quella classe.

Modifica: Scusa, mi sono perso anche i problemi con un parametro. Basta guardare Thread Constructor (ParameterizedThreadStart) e quella pagina include un semplice esempio.

+0

Sì, ha funzionato con un parametro utilizzando ParameterizedThreadStart. Ma voglio usare la stessa soluzione per uno o due o più paramenters – elcool

3

Bene, il metodo diretto consiste nel creare una classe/struttura appropriata che contenga tutti i valori dei parametri e che li trasmetta alla discussione.

Un'altra soluzione in VB10 è quello di utilizzare il fatto che lambda creano un chiusura, che in pratica significa che il compilatore fare quanto sopra automaticamente per voi:

Dim evaluator As New Thread(Sub() 
           testthread(goodList, 1) 
          End Sub) 
+0

Ho letto di questo lambda, ma io sto usando VS 2008 con VB8, credo. Non ho VB10 – elcool

31

Prima di tutto: AddressOf ottiene solo il delegare a una funzione: non è possibile specificare altro (ad esempio, acquisire qualsiasi variabile).

Ora è possibile avviare una discussione in due modi possibili.

  • Passare un Action nel costruttore e solo Start() il thread.
  • passare un ParameterizedThreadStart e in avanti uno argomento oggetto in più per il metodo ha indicato al momento della chiamata .Start(parameter)

considero la seconda opzione un anacronismo da pre-generici, epoca pre-lambda - che hanno concluso al ultimo con VB10.

È potrebbe uso quel metodo grezzo e creare una lista o una struttura che si passa al codice threading in quanto questo singolo parametro oggetto, ma dal momento che ora avere chiusure, si può semplicemente creare il thread su un anonimo Sub che conosce tutte le variabili necessarie di per sé (che è lavoro eseguito per te dal compilatore).

Soo ...

Dim Evaluator = New Thread(Sub() Me.TestThread(goodList, 1)) 

E 'davvero solo quello;)

+0

Bella risposta, ma non ho VB10. * Ho appena modificato la mia domanda – elcool

+0

@elcool: Non penso che ciò richieda. NET 4.0 o VS 2010. Mi sembra 3.5 Netto. – IAbstract

+3

mi dà un errore di compilazione: 'Expression Expected' su Sub – elcool

5

Qualcosa di simile a questo (io non sono un programmatore VB)

Public Class MyParameters 
    public property Name As String 
    public property Number As Integer 
End Class 



Thread newThread = new Thread(AddressOf DoWork); 
Dim parameters As New MyParameters 
parameters.Name = "Arne" 
newThread.Start(parameters); 

public shared sub DoWork(byval data as object) 
{ 
    dim parameters = CType(data, Parameters) 

} 
+3

amico questo non è nemmeno vb – Kiarash

+0

È pseudo codice, ma il concetto è sempre lo stesso. È come lo si fa in .NET. – jgauffin

1

In aggiunta a quanto Dario ha dichiarato circa i delegati si potrebbe eseguire un delegato con diversi parametri:

Predefinite il delegato:

Private Delegate Sub TestThreadDelegate(ByRef goodList As List(Of String), ByVal coolvalue As Integer) 

ottenere un handle al delegato, creare parametri in un array, DynamicInvoke sulla Delegato:

Dim tester As TestThreadDelegate = AddressOf Me.testthread 
Dim params(1) As Object 
params(0) = New List(Of String) 
params(1) = 0 

tester.DynamicInvoke(params) 
+2

DynamicInvoke ... addio sicurezza del tipo. Una risposta valida tuttavia. – Dario

4
Dim evaluator As New Thread(Sub() Me.testthread(goodList, 1)) 
With evaluator 
.IsBackground = True ' not necessary... 
.Start() 
End With 
0

Credo che questo vi aiuterà a ... Creating Threads and Passing Data at Start Time!

Imports System.Threading 

' The ThreadWithState class contains the information needed for 
' a task, and the method that executes the task. 
Public Class ThreadWithState 
    ' State information used in the task. 
    Private boilerplate As String 
    Private value As Integer 

    ' The constructor obtains the state information. 
    Public Sub New(text As String, number As Integer) 
     boilerplate = text 
     value = number 
    End Sub 

    ' The thread procedure performs the task, such as formatting 
    ' and printing a document. 
    Public Sub ThreadProc() 
     Console.WriteLine(boilerplate, value) 
    End Sub 
End Class 

' Entry point for the example. 
' 
Public Class Example 
    Public Shared Sub Main() 
     ' Supply the state information required by the task. 
     Dim tws As New ThreadWithState(_ 
      "This report displays the number {0}.", 42) 

     ' Create a thread to execute the task, and then 
     ' start the thread. 
     Dim t As New Thread(New ThreadStart(AddressOf tws.ThreadProc)) 
     t.Start() 
     Console.WriteLine("Main thread does some work, then waits.") 
     t.Join() 
     Console.WriteLine(_ 
      "Independent task has completed main thread ends.") 
    End Sub 
End Class 
' The example displays the following output: 
'  Main thread does some work, then waits. 
'  This report displays the number 42. 
'  Independent task has completed; main thread ends. 
0

Passo parametro multiplo per VB.NET 3,5

Public Class MyWork 

    Public Structure thread_Data    
     Dim TCPIPAddr As String 
     Dim TCPIPPort As Integer    
    End Structure 

    Dim STthread_Data As thread_Data 
    STthread_Data.TCPIPAddr = "192.168.2.2" 
    STthread_Data.TCPIPPort = 80 

    Dim multiThread As Thread = New Thread(AddressOf testthread) 
    multiThread.SetApartmentState(ApartmentState.MTA) 
    multiThread.Start(STthread_Data)  

    Private Function testthread(ByVal STthread_Data As thread_Data) 
     Dim IPaddr as string = STthread_Data.TCPIPAddr 
     Dim IPport as integer = STthread_Data.TCPIPPort 
     'Your work'   
    End Function 

End Class 
Problemi correlati