locked
Threading and get data RRS feed

  • Question

  • User-1271631458 posted

    Hi everybody,

    I have a problem with threads,this is my demo.I want to get _data at result,I need a demo,thanks.

    Imports System.Threading.Thread
    Public Class Form1

    Private _data As New List(Of String)

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
           Dim thread As Threading.Thread
           Dim str As ArrayList = New ArrayList
           str.Add(1)
           str.Add(2)
           str.Add(3)
           str.Add(4)

    For Each item In str
    thread = New Threading.Thread(AddressOf GetData)
    thread.Start()
    Next
    'result = _data
    End Sub

    Private Sub GetData()
    For i As Integer = 0 To 1000
    _data.Add(i)
    Next
    End Sub

    End Class

    Thursday, August 8, 2019 9:07 AM

All replies

  • User753101303 posted

    Hi,

    Try maybe to find a desktop development forum at https://social.msdn.microsoft.com/Forums/en-US/home Maybe start there by explaining a real (or realistic at least) use case you would like to handle in your desktop app.

    For now having multiple threads doing nothing more than always working on the same data is not a good use case as access needs to be synchronized : http://www.albahari.com/threading/part2.aspx#_Synchronization

    And so yo would use a lock statement resulting in each thread updating the list one after the other (or always competing to add a single element at a time).

    You could have also a look at https://docs.microsoft.com/en-us/dotnet/standard/parallel-programming/task-parallel-library-tpl 

    Thursday, August 8, 2019 9:30 AM
  • User-719153870 posted

    Hi Klaus Shen,

    Private Sub GetData()
    For i As Integer = 0 To 1000
    _data.Add(i)
    Next
    End Sub

    We can see in your GetData() method, nothing is returned?

    Please try below code:

    Public Class Form1
        Private _data As List(Of String) = New List(Of String)()
    
     
    
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
            Dim thread As System.Threading.Thread
            Dim str As ArrayList = New ArrayList()
            str.Add(1)
            str.Add(2)
            str.Add(3)
            str.Add(4)
    
     
    
            For Each item In str
                thread = New System.Threading.Thread(GetData(_data))
                thread.Start()
            Next
    
     
    
            Dim result As List(Of String) = _data
        End Sub
    
     
    
        Private Function GetData(ByVal list As List(Of String)) As List(Of String)
            For i As Integer = 0 To 1000
                list.Add(i)
            Next
    
            Return list
        End Function
    End Class

    Best Regard,

    Yang Shen

    Friday, August 9, 2019 8:27 AM