gpt4 book ai didi

c# - 从析构函数调用 BeginInvoke

转载 作者:太空狗 更新时间:2023-10-29 20:20:14 27 4
gpt4 key购买 nike

我在 WPF 应用程序中有一些代码如下所示:

public class MyTextBox : System.Windows.Controls.TextBox, IDisposable
{
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}

protected virtual void Dispose(bool disposing)
{
Dispatcher.BeginInvoke((Action) delegate
{
// do work on member variables on the UI thread.
});
}

~MyTextBox()
{
Dispose(false);
}
}

dispose 方法从未被显式调用,因此析构函数调用它。在这种情况下,对象似乎会在 BeginInvoke 中的委托(delegate)在 UI 线程上触发之前被销毁。它似乎正在工作。这里发生了什么?这样安全吗?

最佳答案

It seems like in this case the object would be destroyed before the delegate in the BeginInvoke fires on the UI thread

终结器队列用于 UI 消息循环。对象可能会在 UI 线程上调用实际委托(delegate)之前 完成其终结器方法的运行,但这并不重要,因为无论如何委托(delegate)都会排队。

What is happening here?

您正在将终结器中的工作排队到 UI。

Is this safe?

安全是一个广义的术语。我会这样做吗?当然不。从终结器调用对 UI 元素的操作看起来和感觉都很奇怪,特别是考虑到这是一个 TextBox 控件。我建议你完全掌握运行 finalizer guarantees 的内容并且不保证。一方面,运行终结器并不意味着对象会立即在内存中清理干净。

我还建议阅读@EricLippert 的帖子:为什么你所知道的一切都是错误的Part1 & Part2

关于c# - 从析构函数调用 BeginInvoke,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30484870/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com