Thursday, December 2, 2010

Using the ThreadPool - An example as simple as possible

I just posted a code sample using the ThreadPool on a forum so I thought I could also post it here. Who knows, it might prove usefull to someone someday. Basically it simply demonstrate how to create and start new threads with the ThreadPool and how to use delegates with parameters. Here it is :
Imports System.Threading

Public Class Form1

    Delegate Sub UpdateItemValueDelegate(ByVal index As Integer, ByVal value As Integer)
    Public UpdateListItem As UpdateItemValueDelegate = AddressOf UdateItemValue

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Add some values to the listbox for the example
        For i As Integer = 0 To 10
            ListBox1.Items.Add(i.ToString())
        Next
    End Sub

    Private Sub UdateItemValue(ByVal index As Integer, ByVal value As Integer)
        'Set the new item's value
        ListBox1.Items(index) = value
    End Sub

    Private Sub CalculateNewValue(ByVal itemIndex As Integer)
        'Calculate a new value for the given item and call the delegate to set the new item's value
        Dim value As Integer
        value = ListBox1.Items(itemIndex) * 5
        If ListBox1.InvokeRequired Then
            Me.Invoke(UpdateListItem, {itemIndex, value})
        End If
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        'Run a thread for each item in the list
        For i As Integer = 0 To ListBox1.Items.Count - 1
            ThreadPool.QueueUserWorkItem(New WaitCallback(AddressOf CalculateNewValue), i)
        Next
    End Sub
End Class

No comments:

Post a Comment