Skip to main content
 首页 » 编程设计

c#之从不同线程读取 DependencyProperty

2024年02月20日12sxdcgaq8080

我有析构函数问题。这是重现问题的代码:

class DPDemo : DependencyObject 
{ 
    public DPDemo() 
    { 
 
    } 
 
    ~DPDemo() 
    { 
        Console.WriteLine(this.Test);   // Cross-thread access 
    } 
 
    public int Test 
    { 
        get { return (int)GetValue(TestProperty); } 
        set { SetValue(TestProperty, value); } 
    } 
 
    // Using a DependencyProperty as the backing store for Test.  This enables animation, styling, binding, etc... 
    public static readonly DependencyProperty TestProperty = 
        DependencyProperty.Register("Test", typeof(int), typeof(DPDemo), new PropertyMetadata(0)); 
} 

当析构函数运行时,我在 get {SetValue... 行收到 InvalidOperationException。是否有推荐的方法从析构函数或其他一般线程读取依赖属性?

请您参考如下方法:

~ClassName() 函数不是析构函数,而是终结函数。它的作用与 C++ 析构函数截然不同。一旦进入对象生命周期的终结器阶段,就无法可靠地调用该类包含的其他对象,因为它们可能在调用终结器之前已经被销毁。您在终结器中应该做的唯一一件事是释放非托管资源或以正确实现的处置模式调用 Dispose(false) 函数。

如果你需要一个“析构函数”,你需要实现 IDisposable 模式 correctly让您的代码以正确的方式运行。

另请参阅 this question and answer有关编写良好 IDisposable 模式的更多提示,它还有助于解释为什么会出现错误(请参阅他开始谈论终结器的部分)。


回答您的评论:不,它没有。 C# 没有在对象生命周期结束时自动 可靠地调用函数的方法(IDisposable 类 + using 语句代替它)。如果您的对象实现了 IDisposable,则处置该对象是调用者的责任。

在 WPF 应用程序的 OnClose 方法中,您需要调用类的 Save 功能。你根本不需要你的类是IDisposable。

//Inside the codebehind of your WPF form 
public partial class MyWindow: Window 
{ 
    //(Snip) 
 
    protected override void OnClosed(EventArgs e) //You may need to use OnClosing insetad of OnClose, check the documentation to see which is more appropriate for you. 
    { 
        _DPDemoInstance.Save(); //Put the code that was in your ~DPDemo() function in this save function. 
                                //You could also make the class disposeable and call "Dispose()" instead. 
    } 
}