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.
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));
}
}
from Recent Questions - Stack Overflow https://ift.tt/3HNJvAg
https://ift.tt/3zUfZq5
Comments
Post a Comment