Quantcast
Channel: VBForums
Viewing all articles
Browse latest Browse all 15667

System Timer and DataBinding

$
0
0
Hi All,
If I have a class that implements INotifyPropertyChanged, and I have a property in that class that is bound to a label on a form, how do I avoid a Cross-threaded exception if I set the property value from a System.Timers.Timer.Elapsed event handler?

The following code demonstrates the exception.

Thanks for looking
Kevin

VB.Net Code:
  1. Imports System.ComponentModel
  2. Imports System.Timers
  3.  
  4. Public Class Form1
  5.  
  6.     Private thisClass As New aClass
  7.  
  8.     Private lbl As System.Windows.Forms.Label
  9.     Public Sub New()
  10.  
  11.         InitializeComponent()
  12.  
  13.         'create the label and add it to the form
  14.         lbl = New Label
  15.         lbl.Text = "some text"
  16.         Me.Controls.Add(lbl)
  17.  
  18.         'set the data binding and start a timer
  19.         lbl.DataBindings.Add("Text", thisClass, "X")
  20.  
  21.  
  22.     End Sub
  23.  
  24.  
  25. End Class
  26.  
  27. Public Class aClass
  28.     Implements INotifyPropertyChanged
  29.  
  30.     Private WithEvents tmr As New System.Timers.Timer()
  31.     Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged
  32.     Public Sub New()
  33.  
  34.         AddHandler tmr.Elapsed, AddressOf tmr_Elapsed
  35.         tmr.Interval = 1000
  36.  
  37.         tmr.Start()
  38.     End Sub
  39.  
  40.     Private Sub tmr_Elapsed(sender As Object, e As ElapsedEventArgs)
  41.         'change the property value when the timer elapses
  42.         X = Guid.NewGuid.ToString
  43.     End Sub
  44.  
  45.  
  46.     Private _x As String = ""
  47.     Public Property X As String
  48.         Get
  49.             Return _x
  50.         End Get
  51.         Set(value As String)
  52.             _x = value
  53.             RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs("X"))
  54.         End Set
  55.     End Property
  56. End Class

Viewing all articles
Browse latest Browse all 15667

Trending Articles



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