Thread safe observable collection
If you ever wrote something more, then standard UI input-output, you sure got into wide range of exceptions like “The calling thread cannot access this object because a different thread owns it” or “This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread”. What the problem? The problem is old like condom in my wallet world-old, the try to get into resources from different threads. Let me show you some code. Very-very bad code. It’s unbelievable, that this code can ever work.
void onAdd(object sender, RoutedEventArgs e) { new Thread(new ParameterizedThreadStart(addProc)).Start(Resources["source"] as MyCollection); } void onRem(object sender, RoutedEventArgs e) { new Thread(new ParameterizedThreadStart(remProc)).Start(Resources["source"] as MyCollection); } void onMov(object sender, RoutedEventArgs e) { new Thread(new ParameterizedThreadStart(movProc)).Start(Resources["source"] as MyCollection); }
<Window.Resources> <l:MyCollection x:Key="source"/> </Window.Resources> <StackPanel DataContext="{StaticResource source}"> <Button Click="onAdd">Add</Button> <Button Click="onMov">Move</Button> <Button Click="onRem">Remove</Button> <ListBox ItemsSource="{Binding}"/> </StackPanel>
Does not it looks scare? Such code might open unbelievable number of thread. Nothing will stay for it. But, wait. Let’s try to imagine, that we have a bunch of system methods, such as RAM queries, or kind of Amazon web service with million of transactions per second. Even very smart programmer will work with at least 10 threads to update the same collection. So, what to do?
Let’s write Thread Safe Observable Collection, that knows, that it might be called from big number of threads and take care on itself. Sounds good? Let’s start.
First of all we’ll try to get current STAThread (UI) dispatcher. How to do it? Simple. The only place we’ll initialize our collection is in XAML, so default constructor will be called from the thread we need. Now, we save it
Dispatcher _dispatcher; public ThreadSafeObservableCollection() { _dispatcher = Dispatcher.CurrentDispatcher; }
The next step is to override all vital methods of our collection to be invoked from this thread.
protected override void ClearItems() { if (_dispatcher.CheckAccess()) { base.ClearItems();} else { _dispatcher.Invoke(DispatcherPriority.DataBind, (SendOrPostCallback)delegate { Clear(); }); } }
Let’s understand it. First we’re checking if the current thread can access the instance of the object, if it can – we’ll just do our work, but if not, we’ll invoke it in the context of the current thread by sending anonymous delegate with or without parameters.
Why I’m casting the anonymous delegate into SendOrPostCallback? The answer is simple – look into Reflector. You can not implement your delegate with parameter and without return value better
The next step is to take care on locking. We can use old Lock(object) method, but why to do it, if I can continue read my information, while someone writing it. Let’s use ReaderWriterLock. This class makes us able to write and read information concurrently, but still preventing us from writing things at the same simple. Due to the fact, that we are using this lock instance inside at one place we can use UpgradeToWriterLock and DowngradeFromWriterLock instead of real locking. Let’s see how to do it
protected override void InsertItem(int index, T item) { if (_dispatcher.CheckAccess()) { if (index > this.Count) return; LockCookie c = _lock.UpgradeToWriterLock(-1); base.InsertItem(index, item); _lock.DowngradeFromWriterLock(ref c); } else { object[] e = new object[] { index, item }; _dispatcher.Invoke(DispatcherPriority.DataBind, (SendOrPostCallback)delegate { InsertItemImpl(e); }, e); } } void InsertItemImpl(object[] e) { if (_dispatcher.CheckAccess()) { InsertItem((int)e[0], (T)e[1]); } else { _dispatcher.Invoke(DispatcherPriority.DataBind, (SendOrPostCallback)delegate { InsertItemImpl(e); }); } }
Sure, you have to initialize _lock = new ReaderWriterLock() in the constructor. Pay attention, that I’m using the same delegate even with two parameters. It still much better and faster, that write your own delegates for each type of action. Let the framework to do work for you.
After overwriting all vital methods for ObservableCollection, we’re actually, finished. Now, you can derive from your new class and perform the code at the beginning on the article very fast. The smart thread safe observable collection takes care on all the least.
Download and run following example, after playing a bit, check “Fast” checkbox and start pressing buttons as wide spirit. The application will work as requested.
You may also be interested with:
- Real singleton approach in WPF application
- INotifyPropertyChanged auto wiring or how to get rid of redundant code
April 22nd, 2007 · Comments (24)
24 Responses to “Thread safe observable collection”
Leave a Reply
Discover other tags
My tools
- .NET Framework Detector
- Duplicate images finder
- Exchange Security Policy for Windows Mobile Devices Fix
- Gas Price Windows Vista SideBar gadget
- Israel Traffic Information Windows Vista SideBar gadget
- Localization fix for SAP ES Explorer for Visual Studio
- LocTester
- RTL and LTR in Windows Live Writer
- Silverlight controls library
- Snipping tool integration plugin for WLW
- USB FM receiver library
- Vista Battery Saver
- WebCam control for WPF
- Windows Live SkyDrive attachment for Windows Live Writer
- Wireless Migrator
- WPF Virtual Keyboard




January 1st, 2009 at 12:11 am
no need
January 1st, 2009 at 12:11 am
Hello folks, I just went akross this awesome forum through google and I like the especialy this form. I really like the design and the team does its job verry good.
I´m Andrew and I´m pleased to be here
Greetings
January 1st, 2009 at 1:09 am
[...] done. However, I have another problem here. I need to enumerate ThreadSafeObservableColelction. Let’s see the code of [...]
February 18th, 2009 at 6:16 am
Hello…
July 13th, 2009 at 11:51 am
http://pwx.zilerako.thebbs.org/yoredess.html the golden bear jewelry catalog
mortgage money mart
buy super cheap costume jewelry wholesal
July 26th, 2009 at 7:56 pm
Hey!
I want say hi.
I am Andreas, and I from Singapore.
I read for a while here and want introduce me!
Thats all for now
Andreas!
Web Hosting Singapore
August 12th, 2009 at 8:56 pm
Looks like a good forum for whats going on.
Be back later.
Manglerforu
October 1st, 2009 at 11:42 am
Hi
I’ve looked a trailer for the “2012″. I was interested in this theme.
Please advise me a good site on this topic.
And what do you think about the end of the world 2012.
Thanks.
November 9th, 2009 at 3:28 am
Hi.
My PC worked not correctly, many mistakes and buggs. Help me, please to fix errors on my PC.
I used Windows XP.
With best regards,
heabelubs
December 9th, 2009 at 5:01 pm
Procure actual VIAGRA
You craving not be dissapointed
At licence pills recompense the treatment of the facilitate of the like new in every technique
Pick up joined today!
December 13th, 2009 at 5:12 am
Maybe somebody knows where i can find and buy normal and high-quality secateurs online?
Thank you;)
December 17th, 2009 at 10:13 am
Your welcome everyone,
My PC worked not correctly, many errors. Please, help me to fix errors on my computer.
My operation system is Windows7.
Thx,
gomTaxsoontag
December 22nd, 2009 at 7:12 am
SplitVideo is a freeware virtual video clone and split video arrest driver for connecting disparate applications to a only video catching source. Mainly, if you keep a trap camera or video camera connected to your computer, you cannot manoeuvre it in more than anyone application at the changeless fix, and there is no par Windows options that makes it possible. Split Video driver allows you to easily multiply your web-camera (any models), video cameras ( any model: analog or ditial : VHS, DV, TV-IN or TV-tunner ) in video chat or video convention software like Skype.
Download Split Video
January 7th, 2010 at 2:28 am
hallo,
ich hoffe hier im Forum kann mir jemand helfen!
Ich habe versehentlich mehrere songs von meinem MP3 Player verloren. Leider sind die Daten nicht mehr im meinem Papierkorb.
Die Daten waren sehr wichtig für mich! Ich würde die gerne retten.
Wer kennt ne Seite auf der ich Infos dazu finde, wie ich die Daten retten kann??
Vielen Dank schonmal für eure Antworten
danke
January 31st, 2010 at 3:23 pm
There is a guarenteed solution for losing weight and this time it’s a natural solution that works without doubt.
YOU WILL see the results in 1 day! It is a 100% natural fruit that we are offering and there is a FREE trial.
Here you can check it out:
Gaurenteed Weight Loss Link
http://mhlnk.com/676A12E5
THIS WILL HELP AND YOU ONLY PAY AFTER SEEING RESULTS
February 1st, 2010 at 7:38 pm
Hello, Iam new here and I want to start off with a bang! Hence iam sharing this piece of info with you guys here in this great forum http://thesatellitedirect.com/images/satellite%20direct.gif
Now you can Watch Live TV Programs On your PC With the SatelliteDirect Application!
http://satellitedirect.tv/images/main_01.jpg
No Subscriptions or Monthly Fees
No Hardware to Install
No Bandwidth Limits
You Get Over 3,500 Channels
You Get 24/7 Unlimited Access
You Get Auto Channel Updates
Now Available on Mac
You can Watch Online Video Demonstration on Youtube
http://www.youtube.com/watch?v=cggW9PCGtS4
For more information, visit their Website.
Hope it was informative http://www.thesatellitedirect.com/images/satellite%20direct.gif
Cheers.
February 20th, 2010 at 6:00 pm
Fellows
Kaspersky Rescue Disk – intended for testing and treatment of infected computers. Annex applies when it is not possible to cure your computer with antivirus software or utilities of treatment (eg, Kaspersky AVPTool), run under the operating system.
Download Kaspersky Rescue Disk 8.8.1.36
February 25th, 2010 at 6:19 pm
Hello Everyone,
I am new member here
I a short time ago discovered this place and so far i have found a lot of great info here.
I’m looking forward to connecting and adding to the forum.
March 12th, 2010 at 4:25 pm
Hi, my name is Tim. Just wanted to say hi to the forum, I been creeping around here for a while now, but tend to participate more. Looking forward to make some new friends. Ciao!
Tim
NY, NY
June 2nd, 2010 at 6:52 pm
Hello I just lost my job. I have applied to most of the job sites more times than I’d care to recall and applied to 100s of positions. However, i have not been able to find a single good response to my resumes. If anyone knows about any particular place where i can look for a good job, please reply me with the location details. I will be thankful to you for your early response.
June 20th, 2010 at 1:08 am
hello!,if you want to see for free
films online than is allmymovies.biz for
watching movies free online the first choice. Come around take a look. You have nothing to loose.
Thanks for your time.
June 22nd, 2010 at 1:10 am
The sunglasses are one kind to prevent the sunlight intense stimulation to create to the human eye injury vision health care thing, along with the people material cultural level’s enhancement, the cheap sunglasses may or manifests individual style as the cosmetology the special accessories.
July 20th, 2010 at 7:06 am
hello! I’m Saun, and I would like to offer my great site.
Take a look:
Acai Berries – Honest Acai Berry Reviews
July 29th, 2010 at 10:57 am
Interesting blog. Read a few other of your blogged articles and I have to say it is being a daily habit of mine to keep coming back trying to find new stuff lol. Keep up the good work.