自处置类
我有一个管理流程的课程。当在该类上调用 Stop()
或 Dispose()
时,它会首先向进程发送 TCP 命令,要求其自行关闭,然后在 1 秒后返回查看,如果没有关闭,则调用 CloseMainWindow()
,然后再等待几秒钟,如果仍在运行,则调用 Kill()
。
现在我有一个此类的 List<>
来管理一堆进程。当我想从列表中删除它们时,我会手动调用 Dispose()
,然后调用 Remove()
。我想确保在丢失唯一的引用之前调用了 Dispose()。由于调用 Dispose()
至少需要 2 秒才能返回,因此如果我说要删除 5 个项目,则需要一段时间。
所以我打算有另一个名为 SafeDispose()
的函数,它 Invoke()
Dispose()
然后返回。现在,从列表中删除它们并调用 SafeDispose()
而不是 Dispose()
将立即生效,而类本身会缓慢地自行处理。
建议这样做吗?
I have a class that manages a process. When calling Stop()
or Dispose()
on this class, it will first send TCP command to the process to ask it to close itself, then check back in 1 second time, if it's not close, call CloseMainWindow()
, then wait another seconds, if it's still running, call Kill()
.
Now I have a List<>
of this class to manage a bunch of processes. When I would like to remove them from the list, I would manually call Dispose()
, then Remove()
. I want to make sure that I called Dispose()
before I loose the only reference. Since calling Dispose()
will take at least 2 second to return, it will take a while if I have say 5 items to be removed.
So I intended to have another function called SafeDispose()
which Invoke()
Dispose()
then return. Now removing these from the list and calling SafeDispose()
instead of Dispose()
will be immediate while the classes itself disposing themselves slowly.
Is it advisable to do so?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
本质上,您建议“按原样”保留 Dispose,而使用一个辅助方法来异步拆除对象 - 该方法附加到对象上。
可取吗?
也许,引入线程的棘手之处在于随之而来的所有线程混乱。
如果您能以令人满意的方式回答所有问题,那么也许可以。
请记住,您还可以在 UI 中分离一个线程来处理所有过期,并在单个线程中执行此操作(作为另一个选项)
Essentially you are suggesting, leaving Dispose "as is" and instead having a helper method that tears down the object asynchronously - which is attached to the object.
Is it advisable?
Perhaps, the tricky thing about introducing threads is all the threading mess that comes with it.
If you can answer all in a satisfactory way then maybe.
Keep in mind you could also spin off a thread in the UI that handles all expiration and does so in a single thread (as another option)
使用事件代替
Use an event instead
使用异步方法调用来处置对象,然后将它们从列表中删除。
假设您有一个要处理的 foo 类列表,名为 foos。
如果您使用 .net 4.0,则可以使用并行库来执行此操作以提高效率。
编辑 - List.Remove 线程安全的流行需求。
至于异常安全。 Dispose() 方法一开始就不应该抛出异常。
Use asynchronous method invoke to dispose the objects then remove them from the list.
Say you have a list of class foo to dispose called foos.
If you on .net 4.0, you can do this with the Parallel library for more effeciency.
Edit - popular demand for List.Remove thread safety.
As for exception safety. Dispose() method should never throw exception in the first place.