【问题标题】:Retrieving a dp value from another task从另一个任务中检索 dp 值
【发布时间】: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));
    }
}

【问题讨论】:

标签: c#


【解决方案1】:

抱歉,您不能从创建DependencyObject 的线程以外的任何其他线程访问依赖属性。

base class implementation 中的VerifyAccess 方法引发了InvalidOperationException,对此您无能为力(当然,除了确保您只能从调度程序线程访问依赖属性)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-13
    • 1970-01-01
    • 2023-01-24
    • 2016-06-16
    • 1970-01-01
    • 2017-03-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多