0

I'm using Observal.subscribe to run a sub that changes a value of label with this code

 Dim observ As IObservable(Of Long) = System.Reactive.Linq.Observable.Interval(TimeSpan.FromSeconds(10))
    Dim source As New System.Threading.CancellationTokenSource()
    Dim action As Action = (Sub() ChangeLed())
    Dim resumeAction As Action = (Sub() ChangeLed())
    observ.Subscribe(Sub(x)
                         Dim task As New Task(action)
                         task.Start()
                         task.ContinueWith(Sub(c) resumeAction())
                     End Sub, source.Token)

and the changeled() sub mentioned above is by example

 private sub Changeled()
    If PingHost("myhostIP") Then
        label1.Content = "Connected"
    Else
        label1.Content = "Not Connected"
    End If 
 end sub

I have an error says : "The calling thread cannot access this object because a different thread owns it." I know i have to use invoke By dispatcher here but i don't know where. ps:the pingHost is a function that returns true or false based on pinging a host

uramium
  • 17
  • 1
  • 5
  • Possible duplicate of [The calling thread cannot access this object because a different thread owns it](http://stackoverflow.com/questions/9732709/the-calling-thread-cannot-access-this-object-because-a-different-thread-owns-it) – blaze_125 Jan 24 '17 at 14:42
  • I know i have to use invoke By dispatcher here but i don't know where as i use observal.subscribe – uramium Jan 24 '17 at 14:47

1 Answers1

0

You're using two different concurrency models: Task Parallel Library (TPL) and Rx. Ideally you would use only one (Rx) like so:

observ.
    Select(Function(i) Pinghost("myHostIP")).
    ObserveOnDispatcher().
    Subscribe(Sub(pingResult)
                If pingResult Then
                    label1.Content = "Connected"
                Else
                    label1.Content = "Not Connected"
                End If
              End Sub, source.Token)

ObserveOnDispatcher comes from nuget package System.Reactive.Windows.Threading.

If you want to keep your TPL code in there, then I would update ChangeLed as follows:

Private Sub Changeled()
    If PingHost("myhostIP") Then
        this.Dispatcher.Invoke(Sub() label1.Content = "Connected")
    Else
        this.Dispatcher.Invoke(Sub() label1.Content = "Not Connected")
    End If
End Sub
Shlomo
  • 14,102
  • 3
  • 28
  • 43