Retrieving a dp value from another task

I'm using a dp, and I created 2 tasks.

In task1, I new a TestClass. In task2, I want to get Num value, but got error:

Exception thrown: 'System.InvalidOperationException' in WindowsBase.dll
An exception of type 'System.InvalidOperationException' occurred in WindowsBase.dll but was not handled in user code
The calling thread cannot access this object because a different thread owns it.

Note, they must be in different thread for some reason. Actually there are 3 threads, I just made a sample to reproduce it.

enter image description here enter image description here namespace WpfApp1 { /// /// Interaction logic for MainWindow.xaml /// public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            var task1 = new Task(Test1);
            task1.Start();

            var task2 = new Task(Test2);
            task2.Start();

            task1.Wait();
            task2.Wait();
        }

        private TestClass another = null;
        private AutoResetEvent autoResetEvent = new AutoResetEvent(false);

        private void Test1()
        {
            another = new TestClass();
            autoResetEvent.Set();
        }

        private void Test2()
        {
            //Task.Delay(1000);
            autoResetEvent.WaitOne();

            int k = 0;
            k = another.Num;
        }

    }

    public class TestClass : DependencyObject
    {
        public int Num
        {
            get
            {
                return (int)GetValue(NumProperty);
            }
            set { SetValue(NumProperty, value); }
        }

        public static readonly DependencyProperty NumProperty =
            DependencyProperty.Register("Num", typeof(int), typeof(TestClass), new PropertyMetadata(10));
    }
}

Solution 1:

Sorry, but you cannot access a dependency property from any other thread than the one on which the DependencyObject was created on.

It's the VerifyAccess method in the base class implementation that throws the InvalidOperationException and there is nothing you can do about this (apart from making sure that you only access the dependency property from the dispatcher thread of course).