Page 2 of 4 FirstFirst 1234 LastLast
Results 41 to 80 of 149

Thread: Understanding Multi-Threading in VB.Net

  1. #41

    Thread Starter
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    8,598

    Re: Understanding Multi-Threading in VB.Net

    The SynchronizationContext is used to submit methods to run on the thread associated with the context.

    In your case, the SynchronizationContext object belongs to the UI thread therefore whenever a method is executing on any other thread and needs to run a method back on the UI thread, it uses the SynchronizationContext's Send to do so.
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  2. #42
    New Member
    Join Date
    Jul 2012
    Posts
    15

    Re: Understanding Multi-Threading in VB.Net

    Sorry, but it's a bit hard write in english because it's the first time I do it in a forum, and this is a difficult argument
    I used your ThreadExtensions Class, and now i need to call some subs in RemoteClient classes, which are created in the BackgroundWorker thread, from the UI Thread....(from button click event subs and others). How can I do this?

  3. #43

    Thread Starter
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    8,598

    Re: Understanding Multi-Threading in VB.Net

    Well classes in the strictest sense aren't really thread specific, running methods are. That means a single class can have many different methods running at the same time on different threads. You can call the class' methods from the UI thread as you call any method. The only problem with this is when your method intends to interact with an object that another method running on another thread is interacting with. In that case you would need to consider some kind of synchronization so that the two threads don't try to access the object at exactly the same time. If such a condition doesn't exist then you can safely call the method from the UI in the normal way.

    The only reason we even need a SynchronizationContext with multi-threaded objects is because controls are a special case and need to be manipulated on the thread they were created on(usually the UI thread). When controls aren't involve things become much simpler.
    Last edited by Niya; Jul 25th, 2012 at 02:15 PM.
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  4. #44
    New Member
    Join Date
    Jul 2012
    Posts
    15

    Re: Understanding Multi-Threading in VB.Net

    This is exactly what I want...

    Code:
    In that case you would need to consider some kind of synchronization so that the two threads don't try to access the object at exactly the same time.
    How can I do this? I have to call some subs in my RemoteClient class which permits my application to send text to the clients... I call this subs from both threads (UI thread adn BackgroundWorker thread) and It could happen the two threads try to access the sub and the objects used in the sub, at exactly the same time....

  5. #45

    Thread Starter
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    8,598

    Re: Understanding Multi-Threading in VB.Net

    Well calling the same method multiple times from different threads isn't actually a problem. Running methods are really instances of the methods. What you need to look out for are lines of code that access objects outside the scope of the methods for example a private field.

    Consider the following:-
    vbnet Code:
    1. Public Class Test
    2.  
    3.     Public Sub Method1()
    4.         For i = 1 To 100
    5.             Debug.Print(i)
    6.         Next
    7.     End Sub
    8.  
    9. End Class

    You are free to call Method1 as many times as you want from as many threads as you want. If you called it from one thread the same time another thread calls it, then there would be two different instances of the same method running. There is no danger with this. However, imagine this:-
    vbnet Code:
    1. Public Class Test
    2.     Private lstNumbers As New List(Of Integer)
    3.  
    4.     Public Sub Method2()
    5.  
    6.         For i = 1 To 100
    7.             lstNumbers.Add(CStr(lstNumbers.Count))
    8.         Next
    9.  
    10.     End Sub
    11.  
    12.  
    13. End Class

    Now there is a real problem when calling the above Method2 more than once from different threads. This is because these different instances of the running Method2 would be accessing the same list and there is a danger both threads access the list at the same time. The solution would be to synchronize access to the list like this:-
    vbnet Code:
    1. Public Class Test
    2.     Private lstNumbers As New List(Of Integer)
    3.  
    4.     Public Sub Method2()
    5.  
    6.         For i = 1 To 100
    7.             SyncLock lstNumbers
    8.                 lstNumbers.Add(CStr(lstNumbers.Count))
    9.             End SyncLock
    10.         Next
    11.  
    12.     End Sub
    13.  
    14.  
    15. End Class

    SyncLock would block if it was called on the same object, in this case lstNumbers, on another thread. When that other thread passes its End SyncLock then the blocked thread would be allowed to proceed and other calls to SyncLock on lstNumbers from other threads would be blocked in the same manner until it reaches its End SyncLock.
    Last edited by Niya; Jul 25th, 2012 at 05:28 PM.
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  6. #46
    New Member
    Join Date
    Jul 2012
    Posts
    15

    Re: Understanding Multi-Threading in VB.Net

    You're the best vb.net programmer I've never seen... How can I say a big thank you?? Thanks to you I managed to fix issues that plagued me for months!!

  7. #47

    Thread Starter
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    8,598

    Re: Understanding Multi-Threading in VB.Net

    Oh its no problem my friend
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  8. #48
    New Member
    Join Date
    Sep 2012
    Posts
    5

    Re: Understanding Multi-Threading in VB.Net

    Hi!

    First of all, thanks for the great tutorial, it's been very very instructive.
    And now the question, what would be the procedure to use two buttons and two labels that do the same thing, or in my application they would need both differnt inputs from my I/O system? (I'm quite a newbie to this so maybe it's a stuipid question)

    Thanks !

  9. #49

    Thread Starter
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    8,598

    Re: Understanding Multi-Threading in VB.Net

    Tell me more about what you want to do with the I/O system.
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  10. #50
    New Member
    Join Date
    Sep 2012
    Posts
    5

    Re: Understanding Multi-Threading in VB.Net

    Basicly I want to read inputs from it ("start"), next I would activate outputs to activate relays and put tension on my testprobe, next would be to test the output of the testprobe with analog input channels.

  11. #51

    Thread Starter
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    8,598

    Re: Understanding Multi-Threading in VB.Net

    Ok, I don't really know too much about relays and test probes but if I understand correctly, these things you speak are I/O devices and you want to process input on one thread and output on another....is this correct ?
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  12. #52
    New Member
    Join Date
    Sep 2012
    Posts
    5

    Re: Understanding Multi-Threading in VB.Net

    No, I want to use two or more threads that execute the same code but use differnt inputs/outputs, thats why I would need more than one variable in those threads, for example:

    if input(nc) = 1 then
    activate output0(nc)
    end if

    Thread number one would use input 0 and thread number two would use input 8, trough the nc variable, same with the output.
    Maybe I'm just talking weird, sorry if I am

  13. #53

    Thread Starter
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    8,598

    Re: Understanding Multi-Threading in VB.Net

    Oh I see, the real problem is that you want to run the same method on different threads with different parameters. Well in the most basic cases you don't have to do anything special, you can just call the same method more than once each time on a different thread. However, if there is some kind of interaction between them or they are accessing the same resource then we have to cater to it.

    Now, what approach are you taking to want to take with this. In this thread I show two forms of doing straight threaded coding. The first one where I show how to simply execute methods from a Form on different thread and the second way was to make a class with asynchronous methods and events that are raised on the UI thread. Which way are you thinking of ?
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  14. #54
    New Member
    Join Date
    Sep 2012
    Posts
    5

    Re: Understanding Multi-Threading in VB.Net

    I would need the second way is that I would need 2 variables for each thread, the number of thread (nc in the example above) and it's "place", since I've been teached to make a process that's secuencial with select case, each thread would be in another step of the process. For example, the fist thread is still on case number 10 and the second thread on case number 35. Is there some other way to make the same thing but easier?

    And to not complicate things much, yes, they access the same resource, I'm thinking of making some sort of buffer to execute them.

    Thanks

  15. #55

    Thread Starter
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    8,598

    Re: Understanding Multi-Threading in VB.Net

    Ok....I think I kinda get what you're saying now....lets see what you have so far and how we can thread it.
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  16. #56
    New Member
    Join Date
    Sep 2012
    Posts
    5

    Re: Understanding Multi-Threading in VB.Net

    For now I got the following:

    Public Class Counter
    Private context As Threading.SynchronizationContext = Threading.SynchronizationContext.Current

    Public Event CountChanged As EventHandler(Of CountChangedEventArgs)
    Protected Overridable Sub OnCountChanged(ByVal e As CountChangedEventArgs)
    RaiseEvent CountChanged(Me, e)
    End Sub

    Public Sub CountAsync(ByVal paso As Integer)
    ThreadExtensions.QueueUserWorkItem(New Func(Of Integer, String)(AddressOf Count), paso)
    End Sub
    Public Sub CountAsync2(ByVal paso As Integer)
    ThreadExtensions.QueueUserWorkItem(New Func(Of Integer, String)(AddressOf Count), paso)
    End Sub
    Public Function Count(ByVal paso As Integer) As String
    ' Dim startTime As DateTime = DateTime.Now
    Dim e As CountChangedEventArgs

    For i = 0 To paso
    e = New CountChangedEventArgs(i, paso)
    Select Case i
    Case 0
    If context Is Nothing Then
    OnCountChanged(e)
    Else
    ThreadExtensions.ScSend(context, New Action(Of CountChangedEventArgs)(AddressOf OnCountChanged), e)
    End If
    Threading.Thread.Sleep(2000)
    Case 2

    If context Is Nothing Then
    OnCountChanged(e)
    Else
    ThreadExtensions.ScSend(context, New Action(Of CountChangedEventArgs)(AddressOf OnCountChanged), e)
    End If
    Threading.Thread.Sleep(200)
    End Select
    Next

    ' Return "Count took : " + (DateTime.Now - startTime).ToString
    End Function
    End Class

    Public Class CountChangedEventArgs
    Inherits EventArgs

    Private _NumeroThread As Integer
    Private _Paso As Integer

    Public Sub New(ByVal nc As Integer, ByVal paso As Integer)
    _NumeroThread = nc
    _Paso = paso
    End Sub
    Public ReadOnly Property NumeroThread() As Integer
    Get
    Return _NumeroThread
    End Get
    End Property
    Public ReadOnly Property Paso() As Integer
    Get
    Return _Paso
    End Get
    End Property
    End Class


    Public Class ThreadExtensions
    Private args() As Object
    Private DelegateToInvoke As [Delegate]

    Public Shared Function QueueUserWorkItem(ByVal method As [Delegate], ByVal ParamArray args() As Object) As Boolean
    Return Threading.ThreadPool.QueueUserWorkItem(AddressOf ProperDelegate, New ThreadExtensions With {.args = args, .DelegateToInvoke = method})
    End Function

    Public Shared Sub ScSend(ByVal sc As Threading.SynchronizationContext, ByVal del As [Delegate], ByVal ParamArray args() As Object)
    sc.Send(New Threading.SendOrPostCallback(AddressOf ProperDelegate), New ThreadExtensions With {.args = args, .DelegateToInvoke = del})
    End Sub

    Private Shared Sub ProperDelegate(ByVal state As Object)
    Dim sd As ThreadExtensions = DirectCast(state, ThreadExtensions)

    sd.DelegateToInvoke.DynamicInvoke(sd.args)
    End Sub
    End Class
    Public Class Form1

    Private WithEvents m_cn As New Counter

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    m_cn.CountAsync(20)
    End Sub
    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    m_cn.CountAsync2(30)
    End Sub

    Private Sub m_cn_CountChanged(ByVal sender As Object, ByVal e As CountChangedEventArgs) Handles m_cn.CountChanged
    Label1.Text = CStr(e.NumeroThread)
    Label2.Text = CStr(e.NumeroThread)
    End Sub
    End Class
    I have no idea how to do the same thing with two threads. Thanks in advance !

  17. #57

    Thread Starter
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    8,598

    Re: Understanding Multi-Threading in VB.Net

    Why do you have two asynchronous Count methods ? You do realize you can have one and call it as many times as you want right ? And each one will execute on a separate thread. I don't really see much of a problem here. You have to remember that an executing method is actually an executing instance of a method.
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  18. #58
    New Member
    Join Date
    Dec 2007
    Posts
    6

    Re: Understanding Multi-Threading in VB.Net

    Hi,

    I have a question. The following Sub from your tutorial takes an address of the Count function with the 'String' as the return type.

    Code:
        Public Sub CountAsync(ByVal Max As Integer)
            ThreadExtensions.QueueUserWorkItem(New Func(Of Integer, String)(AddressOf Count), Max)
        End Sub
    My question is, is there anyway I can change the code so that it would work with Subs instead of Functions. Since my Connect Sub does not return anything, I don't need it to be a Function ? So, what I mean is the following:

    Code:
        Public Sub ConnectAsync(ByVal IP As String, ByVal Port As Integer)
            ThreadExtensions.QueueUserWorkItem(New Func(Of String, Integer)(AddressOf Connect), IP, Port)
        End Sub
    
        Public Sub Connect(ByVal IP As String, Port As Integer)
            'Some code here
        End Sub
    I have tried something like 'New Sub()' but that obviously did not work.


    Thank you
    Last edited by SNiiP3R; Oct 13th, 2012 at 08:27 PM.

  19. #59
    New Member
    Join Date
    Dec 2007
    Posts
    6

    Re: Understanding Multi-Threading in VB.Net

    Okay, I figured it out. Please ignore my previous post.

    Apparently, when we're dealing with Subs that don't return anything we have to use New Action(). So the above Sub would look something like this,

    Code:
        Public Sub ConnectAsync(ByVal IP As String, ByVal Port As Integer)
            ThreadExtensions.QueueUserWorkItem(New Action(Of String, Integer)(AddressOf Connect), IP, Port)
        End Sub

    I'm still however, not too sure what to do with Subs that have no parameters ? For example,

    Code:
        Public Sub Disconnect()
            ThreadExtensions.QueueUserWorkItem()
        End Sub
    
        Private Sub sockDisconnect()
    
        End Sub
    New Action() in this case is not working for some reason.
    Last edited by SNiiP3R; Oct 13th, 2012 at 09:18 PM.

  20. #60

    Thread Starter
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    8,598

    Re: Understanding Multi-Threading in VB.Net

    Use the non generic Action delegate type.
    vbnet Code:
    1. '
    2.     Public Sub Disconnect()
    3.         ThreadExtensions.QueueUserWorkItem(New Action(AddressOf sockDisconnect))
    4.     End Sub
    Last edited by Niya; Oct 13th, 2012 at 11:05 PM.
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  21. #61
    New Member
    Join Date
    Nov 2012
    Posts
    8

    Re: Understanding Multi-Threading in VB.Net

    Niya, I really have to say, by far this is the-best breakdown I have ever seen of multithreading for vb.net. I was having so much issues trying to figure this out for my self. You put this in plain,easy to follow language. I am forever great-full! As you can see it is 5:30AM and I have not been to sleep and I felt the need to register for the forums just to tell you this, thank you very much.

  22. #62

    Thread Starter
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    8,598

    Re: Understanding Multi-Threading in VB.Net

    Thank you friend....I'm glad it helped you

    I thought it might be helpful to try and explain it in the way I would have liked someone to explain it to me when I didn't know how to do it. I seemed to have hit the mark Thx
    Last edited by Niya; Nov 25th, 2012 at 12:12 PM.
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  23. #63
    New Member
    Join Date
    Feb 2013
    Location
    St. Louis, MO
    Posts
    2

    Re: Understanding Multi-Threading in VB.Net

    Niya, Thank you for providing these examples. I don't know if your still following this thread (as the last post was almost 4 months ago). However in case you are, would you be so kind as to provide an identical example of your count program without utilizing your ThreadExtensions routine. I'm using VB2005 and it will not resolve some of the 'With' instructions you used in the routine. And please don't tell me to upgrade, there are reasons why I'm using VB2005 and .net framework 2.0, which I won't discuss as it is off topic. Threading is a something I haven't had a need to code until now - so I'm new at it. Any help would be appreciated.

    What I'm trying to do is to create a second thread that runs continuously in an endless loop. The code in the loop will read about a dozen Boolean values set from the UI thread, and send them out through the serial port to another device (PLC), then turn around and read some other data back from the serial port. Once the data is read back, it is unpacked and then checked to see if any values have changed since the last read. If so, I want to raise a 'status change' event on the UI thread and pass to the event what changed (which class instance) and the new property value (which can be set from either thread). After raising the event (if necessary), the thread will loop back to the beginning and start the communications again (a monitor program). The UI thread will respond to the event and update the screen accordingly. I have the communications part working. I'm trying to work out the threading - your count program pretty much has the functions I need - only I'm unable to use parts of the ThreadExtensions routine as they will not resolve in VB2005. How else can I do this?

    Thanks.

  24. #64

    Thread Starter
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    8,598

    Re: Understanding Multi-Threading in VB.Net

    Use this one:-
    vbnet Code:
    1. Public Class ThreadExtensions
    2.     Private args() As Object
    3.     Private DelegateToInvoke As [Delegate]
    4.  
    5.     Private Sub New(ByVal delegateArgs As Object(), ByVal delegateInstance As [Delegate])
    6.         Me.args = delegateArgs
    7.         Me.DelegateToInvoke = delegateInstance
    8.     End Sub
    9.  
    10.     Public Shared Function QueueUserWorkItem(ByVal method As [Delegate], ByVal ParamArray args() As Object) As Boolean
    11.         Return Threading.ThreadPool.QueueUserWorkItem(AddressOf ProperDelegate, New ThreadExtensions(args, method))
    12.     End Function
    13.  
    14.     Public Shared Sub ScSend(ByVal sc As Threading.SynchronizationContext, ByVal del As [Delegate], ByVal ParamArray args() As Object)
    15.         sc.Send(New Threading.SendOrPostCallback(AddressOf ProperDelegate), New ThreadExtensions(args, del))
    16.     End Sub
    17.  
    18.     Private Shared Sub ProperDelegate(ByVal state As Object)
    19.         Dim sd As ThreadExtensions = DirectCast(state, ThreadExtensions)
    20.  
    21.         sd.DelegateToInvoke.DynamicInvoke(sd.args)
    22.     End Sub
    23. End Class
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  25. #65
    New Member
    Join Date
    Feb 2013
    Location
    St. Louis, MO
    Posts
    2

    Re: Understanding Multi-Threading in VB.Net

    Thanks a bunch Niya. That works perfectly in VB2005.

    Dale

  26. #66
    Registered User
    Join Date
    Mar 2013
    Posts
    2

    Re: Understanding Multi-Threading in VB.Net

    Hi Niya.
    i have a small question! Can help me.
    example: i have a url: (http://mangafox.me/manga/kingdom_hea...04/c030/1.html). And i wana get comic pictures in this page. Specifically, Downloading 3-4 or more pages in same time to speed up load.
    only way I solved my problem.

  27. #67

    Thread Starter
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    8,598

    Re: Understanding Multi-Threading in VB.Net

    In the section where I show how to do multi-threaded classes, I made a class that executed the count on a non-UI thread. In your case you would have a your download method instead of a count. You simply instantiate multiple classes to perform multiple downloads.
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  28. #68
    Registered User
    Join Date
    Mar 2013
    Posts
    2

    Re: Understanding Multi-Threading in VB.Net

    thanks Niya.

  29. #69
    New Member
    Join Date
    Dec 2007
    Posts
    3

    Re: Understanding Multi-Threading in VB.Net

    Hello Niya. Thanks for writing the article. I'm a beginner in VB so I could pickup first 2-3 posts and messed up afterwards.
    Actually I have a list of files in my program and need to download 2 files simultaneously and on the completion of a file, it start downloading next in the list. and I'm just confused what to do and how to alter the code..
    Will you help me please..

  30. #70

    Thread Starter
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    8,598

    Re: Understanding Multi-Threading in VB.Net

    Does your problem have to do with multi-threading it or downloading the files ? Have you already got the downloading part working ?
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  31. #71
    New Member
    Join Date
    Dec 2007
    Posts
    3

    Re: Understanding Multi-Threading in VB.Net

    downloading all files in a listbox one by one is not an issue, I used for next loop and it did the job. And also I like to mention that I used:
    My.Computer.Network.Download()

    I may use Webclient Download Method but thats not an issue at the moment. Multithreading is the issue..

  32. #72

    Thread Starter
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    8,598

    Re: Understanding Multi-Threading in VB.Net

    Show me the code you're using to download the files.
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  33. #73
    New Member
    Join Date
    Dec 2007
    Posts
    3

    Re: Understanding Multi-Threading in VB.Net

    here it is:
    Code:
            Dim Dir As String = InputBox("Directory", "Dir")
            For i As Integer = 0 To lstLinks.Items.Count - 1
    
    
                Dim targetFile As String = lstLinks.Items(i).ToString
                Dim destFile As String
    
                destFile = "E:\Downloads\" & Dir & "\" & i & ".jpg"
    
    
                Try
                    My.Computer.Network.DownloadFile(targetFile, destFile, "", "", True, 10000, True, FileIO.UICancelOption.DoNothing)
                Catch ex As Exception
                    tbStatus.Text += vbNewLine & "ERROR: File: " & i & " ERR Number: " & Err.Number & ". Description: " & Err.Description & "File Name: " & targetFile
                End Try
    
    
            Next

  34. #74

    Thread Starter
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    8,598

    Re: Understanding Multi-Threading in VB.Net

    I'm going to assume you're using VS2010 and later.

    The simplest way to achieve what you want would be to put the downloading part in its own sub like this:-
    vbnet Code:
    1. '
    2.     Private Sub StartDownloads(ByVal Dir As String)
    3.  
    4.         For i As Integer = 0 To lstLinks.Items.Count - 1
    5.  
    6.  
    7.             Dim targetFile As String = lstLinks.Items(i).ToString
    8.             Dim destFile As String
    9.  
    10.             destFile = "E:\Downloads\" & Dir & "\" & i & ".jpg"
    11.  
    12.  
    13.             Try
    14.                 My.Computer.Network.DownloadFile(targetFile, destFile, "", "", True, 10000, True, FileIO.UICancelOption.DoNothing)
    15.             Catch ex As Exception
    16.                 tbStatus.Invoke(Sub()
    17.                                     tbStatus.Text += vbNewLine & "ERROR: File: " & i & " ERR Number: " & Err.Number & ". Description: " & Err.Description & "File Name: " & targetFile
    18.                                 End Sub)
    19.             End Try
    20.  
    21.  
    22.         Next
    23.  
    24.  
    25.     End Sub

    And call it like:-
    vbnet Code:
    1. '
    2.         Dim Dir As String = InputBox("Directory", "Dir")
    3.  
    4.         'Runs StartDownloads on a thread pool thread
    5.         Threading.ThreadPool.QueueUserWorkItem(Sub() StartDownloads(Dir))

    Now this is really a simple scenario. It doesn't account for progress or knowing when the downloads are finished but its the most straightforward way if you don't require any of the complexities of a more robust file download system.
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  35. #75
    Lively Member
    Join Date
    Feb 2012
    Posts
    106

    Re: Understanding Multi-Threading in VB.Net

    Hello Niya, First of all Thanks for this delicious article. After reading your articles and reply here, I couldn't stop to ask.
    I want to ask How can we pass multiple arguments on a thread.

    Now As you have mentioned before that Thread.Start can accept only one parameter.. But why i am still asking because,

    I have a Procedure which loads a .Txt file on a Listview.. in this function I pass .Txt file path and a Listview name.
    Here I am not sure about how many times this procedure will be called. (It depends on number of .Txt files of a directory)

    In other words, the procedure loads all the .Txt files of a directory on listviews.

    Now my Query is, How to use ThreadPool to load all the .Txt files together. I mean instead of calling procedure one by one , how can i call this procedure to load the next .Txt file while the previous .Txt file is being loaded on the listview?

    Here are the sample of codes i am talking about, Please have a look:
    Code:
    Public Sub LoadDB(ByVal bFile As String, ByVal LvName As ListView)
            Try
                Dim inputstream As New IO.StreamReader(bFile)
                Dim newstr(5) As String
                Dim ttt As String
                    Do While inputstream.Peek <> -1
                        Application.DoEvents()
                        ttt = inputstream.ReadLine().Trim
                            newstr = Split(ttt, vbtab)
                            With LvName.Items.Add(newstr(0).ToUpper)
                                .SubItems.Add(newstr(1).ToUpper)
                                .SubItems.Add(newstr(2).ToUpper)
                                .SubItems.Add(newstr(3).ToUpper)
                                .SubItems.Add(newstr(4).ToUpper)
                            End With
                    Loop
                    inputstream.Close()
    		Catch
    		End Try
    End Sub
    And Normally I am calling it like :

    Code:
    For i = 1 to numberOftxtFiles
    LoadDB(fileDirpath & i.ToString, LvPhH1)
    LoadDB(fileDirpath & i.ToString, LvPhH2)
    Next i
    Even I am calling it like..
    Code:
    For i = 1 to numberOftxtFiles
    Threading.ThreadPool.QueueUserWorkItem(Sub() LoadDB(fileDirpath & i.ToString, LvPhH1))
    Threading.ThreadPool.QueueUserWorkItem(Sub() LoadDB(fileDirpath & i.ToString, LvPhH2))
    Next i

    But it's not working...

    Thanks
    Regards,
    Last edited by green.pitch; Jul 19th, 2013 at 06:00 AM.

  36. #76
    Lively Member
    Join Date
    Feb 2012
    Posts
    106

    Re: Understanding Multi-Threading in VB.Net

    Sorry for dual posting.... Above code was not working due to Cross thread Problem..

    Now after
    CheckForIllegalCrossThreadCalls = False

    it is working... Is it good to Disable CheckForIllegalCrossThreadCalls?

  37. #77

    Thread Starter
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    8,598

    Re: Understanding Multi-Threading in VB.Net

    Quote Originally Posted by green.pitch View Post
    Is it good to Disable CheckForIllegalCrossThreadCalls?
    NO NO NO NO NO! Don't do that at all. You're begging for disasters in the future. I dedicated an entire paragraph towards explaining why you cannot call change control properties from a non-UI thread. I showed at least two ways to properly interact with controls from worker threads. One way by use the Invoke property of controls or by use of a SynchronizationContext object. I strongly suggest you go back and read those particulars again. You should NEVER EVER set CheckForIllegalCrossThreadCalls to False.
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  38. #78
    Lively Member
    Join Date
    Feb 2012
    Posts
    106

    Re: Understanding Multi-Threading in VB.Net

    Ok thanks Niya, I tried to invoke a control on another project... But i am getting error. Please have a look to the following code.

    Code:
      Private Sub LoadFrm(ByVal pIDD As String, ByVal pMsg As String)
            memFrmNum = memFrmNum + 1
            FrmObj(memFrmNum) = New Form2
            If FrmObj(memFrmNum).InvokeRequired Then
                FrmObj(memFrmNum).Invoke(New Action(Of String)(AddressOf LoadFrm), pIDD)
                FrmObj(memFrmNum).Invoke(New Action(Of String)(AddressOf LoadFrm), pMsg)
            Else
                FrmObj(memFrmNum).TextBox1.Text = pIDD
                FrmObj(memFrmNum).Label1.Text = pMsg
            End If
            FrmObj(memFrmNum).Show()
        End Sub
    In above code I'm trying to load a form multiple times. Getting error on 'AddressOf LoadFrm'.

    Please check the attachment.
    ErrorOninvoke.zip

    Regards,

  39. #79

    Thread Starter
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    8,598

    Re: Understanding Multi-Threading in VB.Net

    Quote Originally Posted by green.pitch View Post
    Ok thanks Niya, I tried to invoke a control on another project... But i am getting error. Please have a look to the following code.

    Code:
      Private Sub LoadFrm(ByVal pIDD As String, ByVal pMsg As String)
            memFrmNum = memFrmNum + 1
            FrmObj(memFrmNum) = New Form2
            If FrmObj(memFrmNum).InvokeRequired Then
                FrmObj(memFrmNum).Invoke(New Action(Of String)(AddressOf LoadFrm), pIDD)
                FrmObj(memFrmNum).Invoke(New Action(Of String)(AddressOf LoadFrm), pMsg)
            Else
                FrmObj(memFrmNum).TextBox1.Text = pIDD
                FrmObj(memFrmNum).Label1.Text = pMsg
            End If
            FrmObj(memFrmNum).Show()
        End Sub
    In above code I'm trying to load a form multiple times. Getting error on 'AddressOf LoadFrm'.

    Please check the attachment.
    ErrorOninvoke.zip

    Regards,
    The problem there is that you're are trying to invoke LoadFrm with Action(Of String) when you should be invoking with Action(Of String, String) because LoadFrm has two string parameters. However, you are targeting .Net 2.0 which doesn't seem to offer Action(Of T1, T2) so here is another way to correct it if you're using VS2010:-
    vbnet Code:
    1. '
    2.     Private Sub LoadFrm(ByVal pIDD As String, ByVal pMsg As String)
    3.         memFrmNum = memFrmNum + 1
    4.         If memFrmNum > 1000 Then memFrmNum = 1
    5.         FrmObj(memFrmNum) = New Form2
    6.         If FrmObj(memFrmNum).InvokeRequired Then
    7.             FrmObj(memFrmNum).Invoke(Sub() LoadFrm(pIDD, pMsg))
    8.         Else
    9.             FrmObj(memFrmNum).TextBox1.Text = pIDD
    10.             FrmObj(memFrmNum).Label1.Text = pMsg
    11.         End If
    12.         FrmObj(memFrmNum).Show()
    13.     End Sub
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  40. #80
    Lively Member
    Join Date
    Feb 2012
    Posts
    106

    Re: Understanding Multi-Threading in VB.Net

    Oh ok thanks again Niya . I am very new in vb.net. Now the codes are not showing any error, but Form2 is still hanging after loading.. How can I solve this with Multi threading? Please check the attachment file of my last post.

    After clicking button on the form1, Open notepad.exe... and you will found Form2 will be hanging up.

    How can we do it with Control properties on framework above 2.0?

    If you can make any correction on it, please kindly do it.

    Thanks again,
    regards
    Last edited by green.pitch; Jul 20th, 2013 at 04:03 AM.

Page 2 of 4 FirstFirst 1234 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width