Nicros
Nicros

Reputation: 5203

WPF Threading question

Say I have two usercontrols, UC1 and UC2. A user selects something in UC1, which takes some time so the process is threaded off. UC2 needs to update its view and do some work of its own on another thread when UC1 finishes. But UC2 is dependent on the output of the UC1 background thread so it has to wait until that thread is finished before it begins.

UC1 needs to update an ObservableCollection to update its view when its background thread finishes, as does UC1, asynchronously.

Whats the best way to do this? I have tried just threading them off and firing a message from UC1's thread, but then UC2 cant modify its ObservableCollection because it is not on the right thread- it thinks its on UC1's thread.

Do I need to marshall the message event from UC1 to UC2, is this safe?

How do people normally handle this?

Upvotes: 1

Views: 175

Answers (1)

codekaizen
codekaizen

Reputation: 27439

Both UserControls should live on the same thread. This is how WPF is designed.

Since UC2 depends on an event that UC1 also depends on, I would have UC1 scope the lifetime of the event, and send the message to UC2 when the work is done, or else have UC2 subscribe to the ObservableCollection's CollectionChanged event. They both live on the same UI thread, so marshalling between them is not needed, you just need to marshal the background thread to the respective UserControl.

Upvotes: 2

Related Questions