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
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:
Imports System.ComponentModel Imports System.Timers Public Class Form1 Private thisClass As New aClass Private lbl As System.Windows.Forms.Label Public Sub New() InitializeComponent() 'create the label and add it to the form lbl = New Label lbl.Text = "some text" Me.Controls.Add(lbl) 'set the data binding and start a timer lbl.DataBindings.Add("Text", thisClass, "X") End Sub End Class Public Class aClass Implements INotifyPropertyChanged Private WithEvents tmr As New System.Timers.Timer() Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged Public Sub New() AddHandler tmr.Elapsed, AddressOf tmr_Elapsed tmr.Interval = 1000 tmr.Start() End Sub Private Sub tmr_Elapsed(sender As Object, e As ElapsedEventArgs) 'change the property value when the timer elapses X = Guid.NewGuid.ToString End Sub Private _x As String = "" Public Property X As String Get Return _x End Get Set(value As String) _x = value RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs("X")) End Set End Property End Class