baozi
baozi

Reputation: 709

How to Asynchronous update to ObservableCollection items?

I know it's an old question. Here's some codes. It works fine with BindingOperations.EnableCollectionSynchronization(Quotes, _stocksLock);

private void _source_QuoteArrived(Quote Q)
{
    Quotes.Add(Q);
}

Question 1: In xaml file there's listview binding with Quotes. But why cross threading happens here? My understanding of cross threading is it only happens when you do it explicitly. Like the example below. When you explicitly use an UI element (label1 here), crossing threading error occurs.But I am using data binding here which is twoway. Why do i need EnableCollectionSynchronization here?

 private  void button1_Click(object sender, EventArgs e)
 {
     HttpClient client = new HttpClient();
     string result =  client.GetStringAsync("http://microsoft.com");
     label1.Text = result;
 }

Quetion 2: Assuming there exists cross threading with data binding?The above button1_Clickexample can be solved with async await But Why can't i do sth similar just using async await

private async void _source_QuoteArrived(Quote Q)
{
    await Task.Run(() => Quotes.Add(Q));
}

to update listview in the gui. I tried it with corss threading error.
I thought i messed up some concepts. Plz help.

Upvotes: 0

Views: 2009

Answers (1)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149538

Why do i need EnableCollectionSynchronization here?

If by here you mean your second code example, than you don't need any EnableCollectionSynchronization there. Although your second example wont compile, if done properly, will execute label1.Text = result; on the UI thread, and no cross-thread error should occur. The SynchronizationContext will be in charge of marshaling work back onto the UI thread.

But why can't i do something similar just using async await?

I think you're confusing the usage of the Task Parallel Library and the async-await feature. async-await is a tool which is ment to "ease the pain" of writing asynchronous code. Asynchronousy isn't parallelalism:

When you run something asynchronously it means it is non-blocking, you execute it without waiting for it to complete and carry on with other things. Parallelism means to run multiple things at the same time, in parallel.

As your code is structed right now, you can't use Task.Run to update Quotes, because it is a UI bound property.

Most of the time you'll find the use of async-await working naturally with I/O bound operations.

Upvotes: 1

Related Questions