domenica 30 ottobre 2011

[VB.NET] Gestione Cross Threading ...

Descrizione :
Un esempio su come gestire l'accesso a controlli Forms da threads esterni, scongiurando l'errore di Cross-Thread.

+ Articolo :

Nell'esempio ho una Form ( Form1 ) con un Button "cmd_startthread", e una ListBox "ListBox1", e la Classe "MyThreadClass", che deve aggiungere N Items a ListBox1 da un altro Thread.

Come si può notare da : Delegate Sub AddListItem(ByVal arg As String),
c'è anche un'indicazione molto utile su come gestire Delegates che accettano parametri,
perciò l'esempio è semplice, ma non banale...

1. Codice MyThreadClass :

Public Class MyThreadClass
 
    Private m_form As Form1
 
    Public Sub New(ByVal F As Form1)
        m_form = F
    End Sub
 
    Public Sub Run()
        For i As Integer = 1 To 10
            m_form.Invoke(m_form.myDelegate, New Object() {"Item " & i.ToString})
            Threading.Thread.Sleep(500)
        Next
    End Sub
 
End Class 

2. Codice Form1 :
Public Class Form1
 
    Private myThread As System.Threading.Thread
 
    Delegate Sub AddListItem(ByVal arg As String)
    Public myDelegate As New AddListItem(AddressOf AddListItemMethod)
 
    Private Sub AddListItemMethod(ByVal arg As String)
        ListBox1.Items.Add(arg)
    End Sub
 
    Private Sub ThreadMethod()
        Dim myThreadClassObject As New MyThreadClass(Me)
        myThreadClassObject.Run()
    End Sub
 
    Private Sub cmd_startthread_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmd_startthread.Click
        myThread = New System.Threading.Thread(AddressOf ThreadMethod)
        myThread.Start()
    End Sub
 
End Class

+ Fine Articolo.

Un Click su "Mi Piace" è il modo migliore per ringraziare l'autore di questo articolo.



0 commenti:

Posta un commento

Favorites Twitter Facebook Delicious Digg Stumbleupon More

 
Design by Free WordPress Themes Modificato da MarcoGG