gpt4 book ai didi

c# - 保证代码在 C# 终结器中运行

转载 作者:太空宇宙 更新时间:2023-11-03 20:23:46 24 4
gpt4 key购买 nike

我在写一个ASCOM望远镜驱动,需要保证几个串口命令被发送到示波器以阻止示波器在客户端应用程序移动时移动无法正确断开连接或崩溃。

我试着添加一个看起来像这样的终结器

~Telescope()
{
Common.AbortSlew();
Common.SetTracking(false);
}

它进入 SendSerialPortCommand() 方法然后退出而不实际发送字节在线路上,似乎就在锁定语句之前退出。

可以在这里查看 repo

http://code.google.com/p/ascom-nexstar-telescope/source/browse/NexStar/

终结器在 driver.cs 中,调用的方法在静态类 Common 中

是否有更好或更可靠的方法来完成此任务?

最佳答案

实现IDisposable接口(interface)并在 Dispose 方法中完成您的工作。

您应该看到 Greg Beech 的这篇文章:Implementing and using the IDisposable interface

Instead of destructors, .NET has finalizers which are implemented by overriding the Finalize method defined on the base Object class (though C# somewhat confusingly uses the C++ destructor syntax ~Object for this). If an object overrides the Finalize method then rather than being collected by the GC when it is out of scope, the GC places it on a finalizer queue. In the next GC cycle all finalizers on the queue are run (on a single thread in the current implementation) and the memory from the finalized objects reclaimed. It's fairly obvious from this why you don't want to do clean up in a finalizer: it takes two GC cycles to collect the object instead of one and there is a single thread where all finalizers are run while every other thread is suspended, so it's going to hurt performance.

So if you don't have destructors, and you don't want to leave the cleanup to the finalizer, then the only option is to manually, deterministically, clean up the object. Enter the IDisposable interface which provides a standard for supporting this functionality and defines a single method, Dispose, where you put in the cleanup logic for the object. When used within a finally block, this interface provides equivalent functionality to destructors. The reason for finally blocks in code is primarily to support the IDisposable interface; this is why C++ uses simply try/except as there is no need for a finally block with destructors.

关于c# - 保证代码在 C# 终结器中运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11895833/

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