Quantcast
Channel: VBForums - Visual Basic .NET
Viewing all articles
Browse latest Browse all 27333

Re: Accessing Controls from Worker Threads (JMC)

$
0
0
John mention's we should avoid calling the middle man if we know the UI thread needs access. How ever would it be more suited if we wanted to update more then one control to either invoke the control "If Me.Control.InvokeRequired" or invoke each control individually. Code to make things a little clearer.

We always know the control needs invoking.

Accessing each control using the method invoker.
vb Code:
  1. Public Class MainForm
  2.  
  3.     Private WithEvents m_someWork As New SomeWork
  4.  
  5.     Private Sub MainForm_Load(ByVal sender As System.Object,
  6.                               ByVal e As System.EventArgs) Handles MyBase.Load
  7.         Dim t As New Threading.Thread(AddressOf Me.m_someWork.DoWork)
  8.         t.Start()
  9.     End Sub
  10.  
  11.     Private Sub WorkCompleted(ByVal sender As Object,
  12.                               ByVal e As EventArgs) Handles m_someWork.SomeValue
  13.         Dim value As String = DirectCast(e, SomeValueEventArghs).Value
  14.  
  15.         Me.Label1.Invoke(New MethodInvoker(Sub() Me.Label1.Text = value))
  16.         Me.Label2.Invoke(New MethodInvoker(Sub() Me.Label2.Text = value))
  17.  
  18.     End Sub
  19.  
  20. End Class

Invoking only once

vb Code:
  1. Public Class MainForm
  2.  
  3.     Private WithEvents m_someWork As New SomeWork
  4.  
  5.     Private Sub MainForm_Load(ByVal sender As System.Object,
  6.                               ByVal e As System.EventArgs) Handles MyBase.Load
  7.         Dim t As New Threading.Thread(AddressOf Me.m_someWork.DoWork)
  8.         t.Start()
  9.     End Sub
  10.  
  11.     Private Sub WorkCompleted(ByVal sender As Object,
  12.                               ByVal e As EventArgs) Handles m_someWork.SomeValue
  13.  
  14.         If Me.Label1.InvokeRequired Then
  15.             Me.Label1.Invoke(New Action(Of Object, EventArgs)(AddressOf WorkCompleted), sender, e)
  16.         Else
  17.             Dim value As String = DirectCast(e, SomeValueEventArghs).Value
  18.             Me.Label1.Text = value
  19.             Me.Label2.Text = value
  20.         End If
  21.     End Sub
  22.  
  23. End Class

which is more suited? Invoke each control separate? Or invoking once. Feels like repeated code using the first method. But then seems more logical since we know the UI thread needs invoking.

Viewing all articles
Browse latest Browse all 27333

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>