Thread safe observable collection

22 באפריל 2007

41 תגובות

[This blog was migrated. You will not be able to comment here.
The new URL of this post is http://khason.net/blog/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.


Source code for this article

הוסף תגובה
facebook linkedin twitter email

כתיבת תגובה

האימייל לא יוצג באתר. (*) שדות חובה מסומנים

41 תגובות

  1. Ifeanyi Echeruo1 במאי 2007 ב 20:01

    Your implementation could be simpler by letting the Dispatcher do your thread synchronisation for you (that's why it exists)

    a) Dispatcher.Invoke is a thread safe call.
    b) Any invocations of dispatcher callbacks made by a given dispatcher are always made on the same thread so you dont have to lock inside the callback.

    Ergo…

    protected override void InsertItem(int index, T item)
    {
    object[] e = new object[] { index, item };
    _dispatcher.Invoke(DispatcherPriority.DataBind, (SendOrPostCallback)delegate { InsertItemImpl(e); }, e);
    }

    private void InsertItemImpl(object[] e)
    {
    base.InsertItem((int)e[0], (T)e[1]);
    }

    להגיב
  2. tamir2 במאי 2007 ב 11:28

    You are right in case of Invoke synchonous context, but if you'll look into code sample attached, you'll see, that I'm using asynchnonous invocasion. In this case we should lock items

    להגיב
  3. EndaniDon26 ביולי 2008 ב 9:38

    Hello!

    And you happened by in Russia? I was and should you release is provocative ample supply provinces. Yes at it is a lot of features/strangenesses which not to all foreigners are clear. But what to do… If you go to other motherland it is urgent to get tempered to to it…:)
    But a topic not in it. I was in the Yaroslavl scope, bleeding much it was admirably-bred to me (my perception is there marvellous places) and I wished to look for milieus of this scope and here I maintain collided a vast hard – in Russia the Internet am vigorous developed by a mountainous intractable in means, and not quite patronize jolly much greater hards with it. :( In consequence of that, I and could not assign a moral locale of the Yaroslavl/Yaroslavl precinct. hence also I ask from you the ease
    , it is conceivable at someone there there is a correspondent or is unaffected also as vigorous as I was interested in the affirmed locales.

    להגיב
  4. MaggieInWCs19 באוגוסט 2008 ב 19:09

    My husband and I want to go on a fantastic trip soon. We were looking for ideas. Anyone have any great locations? A way to save some dough would be awesome as well. Traveling is pricey these days.

    להגיב
  5. blowblob20 בספטמבר 2008 ב 4:55

    Hello I'm newbie here and can't find a search on the forum

    Could please someone point me to it.

    Thanks,

    Drew

    להגיב
  6. nicdd23 בספטמבר 2008 ב 1:04

    Hello to everybody!

    Where I can find an introduce yourself thread on the forum?

    Thanks,
    Nic

    להגיב
  7. SallyHilvbaters7 באוקטובר 2008 ב 21:11

    My girlfriend and I want to go on a fantastic trip soon. We were looking for suggestions. Anyone have any great locations? A way to save a little money would be awesome as well. Traveling is expensive these days.

    להגיב
  8. Slitlyalielve7 באוקטובר 2008 ב 23:46

    If you've watched the previous debates, you've noticed the Perception Analyzer at the bottom of the screen. It records the reactions of about 30 "uncommitted" voters – but some say your brain can't devote its full attention to what the debaters are saying and what you're seeing.More..

    by proxrte101a

    להגיב
  9. pixprofnrs8 באוקטובר 2008 ב 5:51

    Hello friends!

    We're proud to inform you that PixProfit(dot)com is hiring right now.
    Online job takes not much efforts.
    We have no such thing as "working hours", thus you can work with our portal when you have free time.
    The job is simple – you need to type in the images you see.
    The payment is from $1 for every 1000 images.
    We pay from $0.5 every weekend via PayPal.
    Best workers have bonuses and better job opportunities.

    Start working with us this week and have better job opportunity in a two weeks.
    If you have any questions do not hesitate to ask, contact the administrator.
    Spare a few minutes to visit PixProfit(dot)com

    להגיב
  10. pornmatedotcom9 באוקטובר 2008 ב 3:23

    hello everyone, I am Cathrine. I'm new here and I just wanted to say hello to everyone, I've actually been reading a lot of posts on this forum for a while but this is my first post here :)

    להגיב
  11. kellyjazzgirl20 באוקטובר 2008 ב 11:37

    Hi,

    Does anyone know if Acai berry or Green Tea is better for weight loss? My aunt told me that she got a free trial of Acai Berry diet pills from this website and that she lost some weight (she had to pay $3.95 for shipping).:
    http://health-fit.info

    I did some research and I found this other website giving free trials of a green tea weight loss patch (this one also has a small shipping charge).:
    http://slimhealth.info

    Which one should I try? Maybe both?

    I read on the net that both Acai Berries and Green Tea fight cancer also, but I'm curious to see how they are for weight loss.

    Thanks!
    Kelly

    להגיב
  12. Florefealtnat4 בנובמבר 2008 ב 6:15

    Did who know this adult site http://adultfinder.my101site.com ?
    Its a free register site. Can i get a adult partner from this site? Thanks

    להגיב
  13. SwigreePrem5 בנובמבר 2008 ב 13:52

    With the new launch of WOW - Wrath of the Lich King soon in Nov,
    how many of you guys will be playing?
    Well currently I am pre ordering mine from Offgamers at only US $39.99,
    if you guys know any cheaper place please post up. Sharing is Caring afterall

    להגיב
  14. maxjimbk5 בנובמבר 2008 ב 14:46

    Hi everyone,

    I am new to this forum blogs.microsoft.co.il and hope that anybody can
    help me with the forex – I am looking for an introduction
    for beginners. I have already a little knowledge about shares. (Hope this is the adequate category.)

    I have the big hope that the recent turbulences in the forex exchange promise
    easy money not only for the experts. Any help is so much appreciated.

    Thanks,
    Max

    להגיב
  15. Biggoga10 בנובמבר 2008 ב 18:43

    Where you are going to meet new year?

    להגיב
  16. Pleameken22 בנובמבר 2008 ב 5:14

    I've Found a place. You will get Opt In & Survey Leads emailed to you 7 day a week
    Leads are 100% opt in and have a ton of data including the time and date stamp so that you can use them in an auto-responder or just email them.
    Many of them will have phone numbers so you can also call them if you want.

    They have:
    Full Name
    Mailing Address
    Email Address
    IP Address
    Date Stamp

    http://trafficadd.net

    להגיב
  17. Fristtard22 בנובמבר 2008 ב 9:12

    Guys fouhd this yesterday and been downloading all the top signle and albums for free. It update every 30mins so, enjoy!

    http://www.ukdreamoutlet.com

    להגיב
  18. DeesyFuence24 בנובמבר 2008 ב 14:37

    Hi

    This is the best way to make cash while surfing the net.
    No need to be "Actively" surfing
    No need to "Click" banners
    No limit to how many hours

    http://22add.com

    להגיב
  19. dryclelen1 בדצמבר 2008 ב 8:12

    90% Christmas discount!

    Our website offers a range of wonderful gifts for various occasions such as holidays,
    weddings, birthdays, wedding anniversary, graduations, kids and other special occasions. Buy millions gifts.
    Secure purchase and friendly support guaranteed

    http://www.millionstocks.com

    להגיב
  20. CartoolaBab2 בדצמבר 2008 ב 19:47

    The Google Game Is Over! The Most Profitable Ppc Champion Is Here To Stay…
    No More Wasting Dollars On Poor Performing Campaigns…

    IMPORTANT: Read this, because the doors
    to Yahoo Cash won't stay open for long.
    Itwent live yesterday, and the 300 spots are already vanishing.

    You can spend thousands on Google Adwords ads, or you
    can spend pennies on Yahoo where the competition's less
    and the payoffs can be huge. Yahoo Cash shows
    you how to do it.
    If you're in a hurry, just go here and see why people
    are saying this is the perfect system for anybody to
    start squeezing maximum profits from PPC ads on Yahoo:

    *************************************************
    WHY THIS IS SO URGENT
    *************************************************

    They're only releasing 300 copies of the system every
    three months so they can provide excellent customer
    support. That's not a gimmick–they mean it. When those
    spots are gone, they're gone.

    That's why you need to get over there, see why this is
    like striking gold, and jump on this before the 300
    spots disappear.

    *************************************************

    This is the system that helped these guys milk over
    $463,000 from ClickBank. Here's the link to check it
    out for yourself:

    http://softflirt.com
    All the best!

    להגיב
  21. drupreipt8 בדצמבר 2008 ב 23:42

    I found this site on the internet and felt I had to share it with you all.
    It doesn't matter what you are interested in, it doesn't matter what you do
    for your day job, in these tough times a little extra is always appreciated.

    I spoke with the owner of the site last night and he asked me to pass the
    word that their doors will close once the site is up and running. People are
    starting to sign up in droves because you will immediately see this is THE
    REAL STUFF. The stuff that the other people making money wish you didn't get
    to know about. You might have heard phrases like this before so all I can
    say is, check it out quickly before it is closed for good.

    I signed up at http://www.theaffiliatepalace.com and they are showing me how
    to make money on the internet. These guys are the real deal, if you don't
    believe me check out their page, they will give you one of their methods
    absolutely free, so that you can see the quality of their service. Just try
    it for yourself, if it doesn't work it's cost you nothing and you've lost
    half an hour of your time, but if it does like it did for me… Oh Boy!

    They teach 5 new methods every month and they also have everything you need
    to start selling online right away, even if you don't have your own product,
    web page or hosting.

    If you are feeling brave, I will see you there.
    http://www.theaffiliatepalace.com

    Thanks for listening and sorry for the interuption.

    All the best

    להגיב
  22. suigussytib20 בדצמבר 2008 ב 13:11

    This is one of those things you see on TV except it happened to me, my girlfriend of 4 years cheated on me with my best friend. We had planned on getting married. At first I was mad and then I was sad but now I want revenge. She ruined me so I'm going to ruin her. I posted all of her private (bedroom) pictures on her own little site http://JessicaBabson.com . Hope you enjoy them and spread the word!

    להגיב
  23. Liccatsnece20 בדצמבר 2008 ב 15:19

    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

    להגיב
  24. Hictstastar21 בדצמבר 2008 ב 5:57

    Just wanted to pass some info along about a microsoft critical update that was in
    the news a couple days ago, you can google for info or I have provided a link below.
    I was sitting on my couch looking at my computer screen and noticed my mouse moving
    around and became irate, you guys be careful.

    http://wchurl.info/32ms-update

    להגיב