I planned on this post to be about UI, but I’m going to defer that until the next post. I said from the start of this series that I would document about everything about building the application from scratch, including my struggles.
And with that I want to mention something that got me scratching my head one too many times. It was with how I used LinqToTwitter. Here is the source code which you can immediately copy/paste into a blank project to reproduce:
Now, if you run this, you will see that only one of the view models will get its state updated. Huh?!
How is that possible? I started getting paranoid so I even added the local state variable “just in case.”
Well, I had to look into the source code of LinqToTwitter to figure out exactly what happened. Here is the code for AsyncCallback:
See what happened? The callback gets overwritten every time you call this method. Even though the call to FirstOrDefault() causes all 3 expressions to evaluate, only the last view model will get values because that’s the with the callback attached.
Lesson of the day: The AsyncCallback extension method for LinqToTwitter is not thread-safe.
So…the question is, how do we make it thread safe? I just replaced wrapped the AsyncCallback with another extension method:Nothing complicated – just a simple wait handle to ensure only 1 thread can go through at a time.
Hopefully upstream fixes this, or at least documents it.