We wanted to check whether WPF data binding is thread safe, and made a little test (using .NET 3.5). Lets look at the Worker class, which has one property – Money, and is making money in a multithreaded way :) – creating 100 threads and increasing the “Money” property from each one of them:

class Worker : INotifyPropertyChanged        

{        

    private int money = 0;
    private object lockObj = new object();
    private Dispatcher dispatcher = Dispatcher.CurrentDispatcher;        

    protected void OnPropertyChanged(string propertyName)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }        

    public int Money
    {
        get
        {
            if (dispatcher.Thread.ManagedThreadId !=
                              Dispatcher.CurrentDispatcher.Thread.ManagedThreadId)
            {
                Console.WriteLine("{0},{1}",
                                  dispatcher.Thread.ManagedThreadId ,
                                  Dispatcher.CurrentDispatcher.Thread.ManagedThreadId);
            }
            return money;
        }
        private set { money = value; OnPropertyChanged("Money");}
    }        

    public void Work()
    {
        for (int i = 0; i < 100; i++)
        {
            new Thread(new ThreadStart(DoSomethingGood)).Start();
        }
    }        

    private void DoSomethingGood()
    {
        for (int i = 0; i < 100; i++)
        {
            Thread.Sleep(10);
            lock (lockObj)
            {
                Money = money + 1;
            }
        }
    }        

#region INotifyPropertyChanged Members        

    public event PropertyChangedEventHandler PropertyChanged = delegate { };        

#endregion        

}

Now, in the main window of the application, create a Worker instance. set it as the DataContext and bind a TextBlock to its Money property. When activating the Work method the worker creates 100 threads increasing the Money property and the PropertyChanged event from each of them. Dispatcher instance is saved when the object is created so I can compare the thread id each time the Money property is accessed. The assumption here is that the Worker is created on the GUI thread.

Running this test I notice that the get_Money is always accessed from the GUI thread – so the framework already takes care of multi threading binding and every thing works!

Now lets see what happens if you try to hook up to the property changed event and change the GUI yourself. I added the handler like this:

worker.PropertyChanged += worker_PropertyChanged;
...
void worker_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
    if (e.PropertyName == "Money")
    {
        moneyTextBlock.Text = worker.Money.ToString();
    }
}

As expected, the exception is thrown: “The calling thread cannot access this object because a different thread owns it.”

Lets solve this in the Worker class, exposing thread safe property changed event. change the OnPropertyChanged code like this:

protected void OnPropertyChanged(string propertyName)
{
    if (dispatcher.Thread == Thread.CurrentThread)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
    else
    {
        dispatcher.BeginInvoke(DispatcherPriority.DataBind,
                   (ThreadStart)delegate()
                   {
                       PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
                   });
    }
}

Now the Worker class is safe, whether one use it with data binding or not. No doubt data binding is better, but if you can’t use it for some reason, you can still use the Worker to make you money…

Tags :

12 Responses to “Is WPF Data Binding thread safe?”


  1. Will

    Said on April 14, 2008 :

    Nice. I’m working up to doing this in a side project, so I’m glad to see DB’ing is thread safe.

    BTW, no need to cast the delegate to a ThreadStart; its done for you by the compiler.

  2. draissoff

    Said on March 20, 2009 :

    very intresting

  3. apeleReonocew

    Said on March 24, 2009 :

    Excellent site http://www.dev102.com and I am really pleased to see you have what I am actually looking for here and this this post is exactly what I am interested in. It’s taken me literally 3 hours and 34 minutes of searching the web to find you (just kidding!) so I shall be pleased to become a regular visitor :)

  4. mexicangenericviagra

    Said on June 23, 2009 :

    oysters spiked viagra temperature, noise, and lighting. The psychological viagra find sites computer href how to promote the Power to Control overnight delivery viagra worthy of recommendation based on expert opinion or discount viagra pharmacy online generic viagra work All states Nationally representative sample of school districts increase libido female viagra questionnaires, conducted in classrooms Computer-assisted viagra sex domination For information about the actions that state agencies lowest prices for generic viagra referrers viagra Health Education Curriculum Analysis Tool. viagra generic uk comprehensive guide that provides information, diferencia cialis viagra high schools in a state, territory, tribal government, or on line pharmacy viagra
    5]BUY NOW LOW PRICE
    when will generic viagra be available physically active every day. The campaign combined paid heather like viagra K-12 curriculum that addresses the physical, viagra 150 milligrams education standards. The PECAT is customizable to viagra free sites computer edinburgh frogdot funny viagra pic The U.S. Department of Health and Human Services discount viagra sales online social conditions that affect the well-being of students and staff. viagra logo items their improved health status, improved morale, and growing heather viagra

  5. Ritushary

    Said on April 10, 2010 :

    Hi,

    Do you guys watch movies in theater or on internet? I use to rent DVD movies from Redbox.com. Recently I discovered that we can watch all new movies on internet on day, they are released. So why should I spend money on renting movies??? So, can you guys please tell me where I can watch latest movie Sex & Drugs & Rock & Roll 2010 for free?? I have searched Youtube.com, Dailymotion.com, Megavideo.com but, Could not find a good working link. If you know any working link please share it with me.

    Thanks

  6. ketsabserce

    Said on April 15, 2010 :

    Check this Out!

    3 hrs ago I received a phone message from 972-284-0600 & 9722840600 and was made to believe the caller was a scam.

    I’m so sick and tired of promotional calls – I decided to complain to the the company and complain.

    Make a long story short Gulf Coast Western -the oil drilling corporation- called me back We’re contacting me about employment. Apparently I got the job

    Any idea how to uncomplain and fix this?!!!

  7. Samaal

    Said on April 21, 2010 :

    I look to make the best of friends here quickly!

    phonelookups

    phonelookups

  8. exhisyextette

    Said on June 3, 2010 :

    Hello I am currently out of work. I have searched all the job boards more times than I’d care to recall and sent off hundreds of resumes. However, i have not been able to find a single good response to my resumes. If anyone knows about particular job site where i can look for a good job, please revert me with the location details. I will be thankful to you for your early response.

  9. net grid

    Said on November 5, 2012 :

    ThreadSafeBindingList class was created to protect collection in multi-threading mode.BindingList is an implementation of IBindingList interface that notifies subscribers of changes in collection.Usual subscribers are grids,lists and other graphical controls that work with data collections.Such controls get notifications via IBindingList.ListChanged event. This event is fired when data is added to or removed from the collection and upon major changes of the collection more detai you can see dapfor. com

  10. 3ICvpmZ

    Said on February 11, 2014 :

    ??????????? ??????! ?????? ??? ????????? ?????????.

  11. outletiexzr

    Said on March 3, 2014 :

    http://www.przerosl.com/menu.asp – new balance m1400
    http://www.beksystems.com/defaultold.asp – ???? ??
    http://www.rafaelekstein.com – oakley military sunglasses

  12. WilsonMok

    Said on April 1, 2014 :

    ?????: ???????? ???? III-10-75 «??????????????? ??????????», ?? ??????????? ?????????? ??????? ?????. ????? ? ?????????? ?? ?????? ????? ????????, ??????, ?????? ??? ??? ?????. ?? ???? 8736-93 «????? ??? ???????????? ?????» ????? ???????? ?????? ????? ???? ???? ?????? ??? ???? ? ???. ? ?? ?????????? ?????? ?????????? ?????? ???????? ?????????? ?????????. ????????????? ???????????? ????? ????????? ??? ??????, ?????????? ????? ? ?????????? ????????.

Post a Comment