Results 1 to 16 of 16

Thread: [RESOLVED] Threading & Accessing controls repeatidly.

  1. #1

    Thread Starter
    Fanatic Member
    Join Date
    Dec 2009
    Posts
    547

    Resolved [RESOLVED] Threading & Accessing controls repeatidly.

    Hi, Whats the best way to handle updating the UI lots of times from a worker thread. Depending on speed the UI may need updating 3/4 times in a second. Say if the overall task takes 1 minute to complete, we could have over 100 updates in that given time.

    My problem is it feels like i am creating a worker thread just to constantly jump back to the UI thread.

    do you think the SynchronizationContext class would be better suited then what i am doing below.

    vb Code:
    1. Public Class MainForm
    2.  
    3.     Private Event SomeThingChnaged As EventHandler(Of SomeThingChnagedEventArghs)
    4.  
    5.     Private Sub StartButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles StartButton.Click
    6.         Dim t As New System.Threading.Thread(AddressOf DoWork)
    7.         t.Start()
    8.     End Sub
    9.  
    10.     Private Sub DoWork()
    11.         ' Do work
    12.         RaiseEvent SomeThingChnaged(Me, New SomeThingChnagedEventArghs("Data"))
    13.         'do work
    14.         RaiseEvent SomeThingChnaged(Me, New SomeThingChnagedEventArghs("Data"))
    15.         ' and so on
    16.     End Sub
    17.  
    18.     Private Sub UpdateInterface(ByVal sender As Object, ByVal e As EventArgs) Handles Me.SomeThingChnaged
    19.         If Me.StatusTextBox.InvokeRequired Then
    20.             Me.StatusTextBox.Invoke(New Action(Of Object, EventArgs)(AddressOf UpdateInterface), sender, e)
    21.         Else
    22.             Dim value As String = DirectCast(sender, SomeThingChnagedEventArghs).Value
    23.             Me.StatusTextBox.AppendText(value & vbNewLine)
    24.         End If
    25.     End Sub
    26.  
    27. End Class

  2. #2
    PowerPoster Evil_Giraffe's Avatar
    Join Date
    Aug 2002
    Location
    Suffolk, UK
    Posts
    2,555

    Re: Threading & Accessing controls repeatidly.

    Invoking back to the UI 3 or 4 times a second will be fine. If you want to get rid of some of the boilerplate you could look at using a BackgroundWorker instead of an explicit Thread, though you'll have some new boilerplate associated with the BGW, but at least you can get rid of the Invoke code. SychronisationContext won't help much because you still need to Post or Send, what you've got does basically the same thing (I haven't checked, but I'd bet that it actually uses the SynchronisationContext under the hood).

    Another point about the BGW is that I believe it'll use a thread from the ThreadPool, but since you're talking about a single thread that will run for a minute or so, the overhead of creating your own Thread is negligible to the point of non-existence.

  3. #3
    Old Member moeur's Avatar
    Join Date
    Nov 2004
    Location
    Wait'n for Free Stuff
    Posts
    2,712

    Re: Threading & Accessing controls repeatidly.

    You might want to consider using BeginInvoke instead of Invoke. This way your background code doesn't have to wait for your foreground updates. This is assuming you don't need strict synchronization between threads.

  4. #4

    Thread Starter
    Fanatic Member
    Join Date
    Dec 2009
    Posts
    547

    Re: Threading & Accessing controls repeatidly.

    Quote Originally Posted by Evil_Giraffe View Post
    Invoking back to the UI 3 or 4 times a second will be fine. If you want to get rid of some of the boilerplate you could look at using a BackgroundWorker instead of an explicit Thread, though you'll have some new boilerplate associated with the BGW, but at least you can get rid of the Invoke code. SychronisationContext won't help much because you still need to Post or Send, what you've got does basically the same thing (I haven't checked, but I'd bet that it actually uses the SynchronisationContext under the hood).

    Another point about the BGW is that I believe it'll use a thread from the ThreadPool, but since you're talking about a single thread that will run for a minute or so, the overhead of creating your own Thread is negligible to the point of non-existence.
    so if it uses SynchronisationContext under the hood is it not best to just use it?

    This is assuming you don't need strict synchronization between threads.

    sorry not following this bit? But noted on begin invoke.

  5. #5
    PowerPoster Evil_Giraffe's Avatar
    Join Date
    Aug 2002
    Location
    Suffolk, UK
    Posts
    2,555

    Re: Threading & Accessing controls repeatidly.

    Quote Originally Posted by kayleigh View Post
    so if it uses SynchronisationContext under the hood is it not best to just use it?
    I would say not. The various Invoke methods on controls provide a simpler interface for invoking updates to the UI from background threads.

  6. #6

    Thread Starter
    Fanatic Member
    Join Date
    Dec 2009
    Posts
    547

    Re: Threading & Accessing controls repeatidly.

    Well thats my worry resolved

    Code:
        
    Private Sub UpdateInterface(ByVal sender As Object, ByVal e As EventArgs) Handles Me.SomeThingChnaged
    If Me.StatusTextBox.InvokeRequired Then
    Me.StatusTextBox.Invoke(New Action(Of Object, EventArgs)(AddressOf UpdateInterface), sender, e)
    Quick note on the invoke though. Am i using the action delegate correctly since i am passing a custom event(Of T

  7. #7
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    38,988

    Re: Threading & Accessing controls repeatidly.

    One thing you might consider is pooling changes, if that's possible. While it might be fine to update a UI 3-4 times a second, the result is a UI that is jumping around spastically.
    My usual boring signature: Nothing

  8. #8
    Hyperactive Member
    Join Date
    Jan 2010
    Posts
    259

    Re: Threading & Accessing controls repeatidly.

    Quote Originally Posted by kayleigh View Post
    Well thats my worry resolved

    Code:
        
    Private Sub UpdateInterface(ByVal sender As Object, ByVal e As EventArgs) Handles Me.SomeThingChnaged
    If Me.StatusTextBox.InvokeRequired Then
    Me.StatusTextBox.Invoke(New Action(Of Object, EventArgs)(AddressOf UpdateInterface), sender, e)
    Quick note on the invoke though. Am i using the action delegate correctly since i am passing a custom event(Of T
    There is nothing wrong with the use of the action delegate, you could just as easily use a anonymous method, but that is mostly up to the programmer.

    Does that code execute? I would have to look it up, but I thought Invoke took and array of objects rather than multiple parameters like you have defined, but like I said, I would have to look at msdn again to make sure.

  9. #9
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    8,598

    Re: Threading & Accessing controls repeatidly.

    Quote Originally Posted by wakawaka View Post
    I would have to look it up, but I thought Invoke took and array of objects rather than multiple parameters like you have defined, but like I said, I would have to look at msdn again to make sure.
    Yes it does take an array but the parameter's declaration in the .Net Framework's source code was preceded by the ParamArray(or its C# equivalent if it was written in C#) keyword which tells the compiler to treat that argument and every argument after it as elements of the array itself.
    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. #10
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    8,598

    Re: Threading & Accessing controls repeatidly.

    Quote Originally Posted by Evil_Giraffe View Post
    (I haven't checked, but I'd bet that it actually uses the SynchronisationContext under the hood).
    vbnet Code:
    1. Private Sub InvokeMarshaledCallback(ByVal tme As ThreadMethodEntry)
    2.     If (Not tme.executionContext Is Nothing) Then
    3.         If (Control.invokeMarshaledCallbackHelperDelegate Is Nothing) Then
    4.             Control.invokeMarshaledCallbackHelperDelegate = New ContextCallback(AddressOf Control.InvokeMarshaledCallbackHelper)
    5.         End If
    6.         If (SynchronizationContext.Current Is Nothing) Then
    7.             WindowsFormsSynchronizationContext.InstallIfNeeded
    8.         End If
    9.         tme.syncContext = SynchronizationContext.Current
    10.         ExecutionContext.Run(tme.executionContext, Control.invokeMarshaledCallbackHelperDelegate, tme)
    11.     Else
    12.         Control.InvokeMarshaledCallbackHelper(tme)
    13.     End If
    14. End Sub

    Calling Invoke ultimately leads to the function above inside the Control class so yes it does use the SynchronizationContext class. Although it doesn't actually use it here, I doubt we would be seeing it here if it wasn't part of the process. This is so complex though, I'm having a hard time finding where it actually uses it. The call chains involved in an Invoke is frighteningly deep.
    Last edited by Niya; Feb 7th, 2013 at 04:26 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

  11. #11

    Thread Starter
    Fanatic Member
    Join Date
    Dec 2009
    Posts
    547

    Re: Threading & Accessing controls repeatidly.

    Quote Originally Posted by Shaggy Hiker View Post
    One thing you might consider is pooling changes, if that's possible. While it might be fine to update a UI 3-4 times a second, the result is a UI that is jumping around spastically.
    Can you explain this please

    Nya how do you guys get to the "bottom" code if that make sense. Like seeing under the hood. ty

  12. #12
    PowerPoster Evil_Giraffe's Avatar
    Join Date
    Aug 2002
    Location
    Suffolk, UK
    Posts
    2,555

    Re: Threading & Accessing controls repeatidly.

    Quote Originally Posted by kayleigh View Post
    Can you explain this please
    What SH meant is that if the UI is changing every .25s due to updates from background processing, the user could get confused. However, since you're just appending some text, it's not really going to be a problem in this case.

  13. #13

    Thread Starter
    Fanatic Member
    Join Date
    Dec 2009
    Posts
    547

    Re: Threading & Accessing controls repeatidly.

    Ahhh. TY Evil_Giraffe, One last question. Is there a reason to not use SynchronizationContext over the way iv chosen? I seem to be drawn to using SynchronizationContext, dont know why.

  14. #14
    PowerPoster Evil_Giraffe's Avatar
    Join Date
    Aug 2002
    Location
    Suffolk, UK
    Posts
    2,555

    Re: Threading & Accessing controls repeatidly.

    Because it's a more primitive abstraction. You aren't trying to synchronise threads, you're trying to update the UI from a background thread. WinForms provides an abstraction that does exactly what you want, so why would you want to go a level lower and use the primitives to re-code exactly what WinForms provides, except with the added excitement of probably making a subtle error that means your program doesn't work sometimes? (And given that this is a threading construct, by "sometimes" you can be sure that doesn't include ever in your development environment, only when your users are using it.)

  15. #15

    Thread Starter
    Fanatic Member
    Join Date
    Dec 2009
    Posts
    547

    Re: Threading & Accessing controls repeatidly.

    Sorted. Thanks every One xx

  16. #16
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    8,598

    Re: Threading & Accessing controls repeatidly.

    Quote Originally Posted by kayleigh View Post
    Nya how do you guys get to the "bottom" code if that make sense. Like seeing under the hood. ty
    .Net Reflector and an insane determination to dig through call chains.
    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

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