C#弱引用在表单中使用它时会有误解释吗? [英] C# weakreference misinterpretation while using it for forms?
问题描述
亲爱的专家
看起来我不明白 WeakReference
。我的目标是通过WeakReference观察表单的生命周期。
在我的MainForm中,我使用弱引用创建Formtest:
Dear experts
It looks like I don't get the point on WeakReference
. My goal is to let "observe" lifetime of a form by WeakReference.
In my MainForm I create a Formtest using a weak reference:
public partial class FormMain : Form
{
private WeakReference weakRefFormTest= null;
private void buttonNewForm_Click(object sender, EventArgs e)
{
if (weakRefFormTest == null)
{
// Create WeakReference and the form
weakRefFormTest = new WeakReference(new FormTest());
((Form)weakRefFormTest.Target).Show();
}
else
{
// Check form alive *1)
Form formTest = (Form)weakRefFormTest.Target;
if (formTest != null)
{
formTest.Visible = !formTest.Visible;
}
}
}
...
......
}
* 1)我希望在关闭testForm后,(Form)weakRefFormTest.Target
将为null。但它不是这样的,它会给我一个有效的形式。关闭formTest后, weakRefFormTest.IsAlive
也返回true。然后使用代码中的表单抛出一个 System.ObjectDisposedException
你能指出我做的事吗不明白,我哪里错了?
注意:我知道我可以订阅Form.Closed-Event,但是我不喜欢这种方法。
非常感谢您提前。
我尝试了什么:
请参阅问题中的代码段。
*1) Here I expect, that (Form)weakRefFormTest.Target
will be null after closing the testForm. But it is not like this, it will give me always a "valid" form. Also weakRefFormTest.IsAlive
returns true after closing formTest. And using then the form in the code throws an System.ObjectDisposedException
Can you point me out what I do not understand, where I'm wrong?
N.B: I'm aware I could subscribe for Form.Closed-Event, but I don't like this approach.
Thank you very much in advance.
What I have tried:
See code snippet in the question.
推荐答案
查看文档:WeakReference.Target Property(System) [ ^ ]
并且它声明:
Look at the documentation: WeakReference.Target Property (System)[^]
And it states that:
Property Value
Type: System.Object
null if the object referenced by the current WeakReference object has been garbage collected; otherwise, a reference to the object referenced by the current WeakReference object.
仅仅因为它已关闭,并不意味着它已被垃圾收集器释放 - 请记住,垃圾收集器只会被踢进内存不足时执行,或者在对象上调用Dispose 。关闭表单既不会执行这些操作,也不会在用户填写完表单后按下确定后访问表单的内容:
Just because it is closed, does not mean that it has been deallocated by the Garbage Collector - remember that the garbage collector is only ever kicked into action when memory runs low, or Dispose is called on an object. Closing a form does neither of those things, or you would not be able to access the content of a form once the user had finished filling it in and pressed "OK":
frmLogin f = new frmLogin();
if (f.ShowDialog() == DialogResult.OK)
{
string username = f.UserName;
...
}
如果您想知道表格何时关闭,您需要使用该事件,而不是弱参考。
:doh:我需要更多的咖啡因... [/ edit]
If you want to know when a form is closed, you need to use the event, not a weak reference.
[edit]:doh: I need more caffeine...[/edit]
这篇关于C#弱引用在表单中使用它时会有误解释吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!