C# 自毁对象

huangapple go评论61阅读模式
英文:

C# Self destroy object

问题

我有一个独立运行的表单(自己运行;加载数据,显示几秒钟然后关闭)

我一直使用new EventListPopup().Show();来调用它,并且依赖于new Timer {Enabled = true, Interval = 5000}.Tick += (s,e) => {Close(); Dispose()}来自毁对象。

如果我在计时器中的任何行上设置断点,我可以看到它没有被销毁,计时器每5秒重复一次(因此确认每次显示弹出窗口时,都会向已创建实例池添加新实例)

是否有一种有效的确认方法允许我自毁对象?绝对不会在其他地方使用它(它尽可能临时)

谢谢

英文:

I have a form that operates independently (by itself; loads data, displays it for a few seconds and closes itself)

I have been calling it with new EventListPopup().Show();, and was counting on new Timer {Enabled = true, Interval = 5000}.Tick += (s,e) => {Close(); Dispose()} to self destroy the object.

If I set a break point on any line within the timer, I can see that it is not destroyed, and the timer repeats every 5 seconds (thus confirming that every time I display the popup, a new instance is added to a pool of already created instances)

Is there a valid confirmed way which allows me to self destroy the object? There is absolutely no way it would be used somewhere else (it is as temporary as it gets)

Thanks

答案1

得分: 5

你正在处理对象本身,而不是计时器。你没有对计时器的引用,所以你的原始代码无法调用它的Dispose方法。处理对象而不使用它可能最终导致计时器被垃圾回收,但也可能不会,因为事件处理程序可以阻止对象被垃圾回收。

以下代码将手动禁用计时器,然后对其进行处理。

var timer = new Timer { Enabled = true, Interval = 5000 };
timer.Tick += (s, e) => { timer.Enabled = false; timer.Dispose(); Close(); Dispose(); }

Jeroen的评论是一个更好的答案,因为它是解决原始问题的更好方式。你可能需要使用Dispatcher/BeginInvoke来确保操作在正确的线程上执行。

计时器可以是一个很好的解决方案,用于具有定期间隔的定时器或需要定期启用/禁用的定时器。

英文:

You're Disposing the object itself, not the Timer. You don't have a reference to the Timer so your original code can't call Dispose on it. Disposing the object and not using it may eventually lead to the timer being garbage collected, but maybe not since event handlers can keep an object from being garbage collected.

The following code will manually disable the timer and then dispose it.

var timer = new Timer { Enabled = true, Interval = 5000 };
timer.Tick += (s, e) => { timer.Enabled = false; timer.Dispose(); Close(); Dispose(); }

Jeroen's comment is a better answer in that it's a better way to solve the original problem. You may need to use Dispatcher/BeginInvoke for the action to happen on the right thread.

Timers can be a good solution for a timer with a recurring interval or that have to be enabled/disabled regularly.

答案2

得分: 0

Task.Delay(TimeSpan.FromSeconds(5)).ContinueWith(_ => this.Invoke(new Action(() => Close()))); 解决了这个问题。
感谢两位!

英文:

Task.Delay(TimeSpan.FromSeconds(5)).ContinueWith(_ => this.Invoke(new Action(() => Close()))); solved the problem.
Thanks to both!

huangapple
  • 本文由 发表于 2023年2月8日 19:06:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/75384871.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定