【发布时间】:2022-01-14 05:15:41
【问题描述】:
我正在使用 dp,我创建了 2 个任务。
在 task1 中,我新建了一个 TestClass。在task2中,我想获取Num值,但是报错:
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.
注意,由于某种原因,它们必须在不同的线程中。实际上有3个线程,我只是做了一个样本来重现它。
命名空间 WpfApp1 { /// /// MainWindow.xaml 的交互逻辑 /// 公共部分类 MainWindow : 窗口 { 公共主窗口() { 初始化组件(); }
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));
}
}
【问题讨论】:
-
不,上面提到的答案与 ui 线程有关。我现在有 3 个线程。
-
调用线程不能访问这个对象,因为另一个线程拥有它 -> 你不能从非ui线程访问uit对象。
标签: c#