线程安全一次性 [英] Thread safe disposable

查看:84
本文介绍了线程安全一次性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在处置IDisposable资源时,我需要确保线程安全.资源在内存中被多次缓存.当从缓存中逐出条目时,我们有一个调用Dispose()的回调.

I need to ensure thread safety when disposing an IDisposable resource. The resource is cached multiple times in memory. When entries are evicted from the cache we have a callback that calls Dispose().

因此,如果资源被缓存了三次,我们将调用Dispose()三次.

Therefore if the resource is cached three times, we'll call Dispose() three times.

IDisposable资源负责确保线程安全或调用方吗?

Is it the responsibility of the IDisposable resource to ensure thread safety or the caller?

推荐答案

答案取决于您要处置的对象是否遵守准则.

The answer depends on whether the objects you want to dispose adhere to the guidelines or not.

如果这样做会使事情变得简单,请从 IDisposable.Dispose :

If they do some things get simpler, from IDisposable.Dispose:

如果多次调用对象的Dispose方法,则该对象必须忽略第一个调用之后的所有调用.如果多次调用其Dispose方法,则该对象不得引发异常.资源已经处置后,除Dispose以外的实例方法可能会引发ObjectDisposedException.

If an object's Dispose method is called more than once, the object must ignore all calls after the first one. The object must not throw an exception if its Dispose method is called multiple times. Instance methods other than Dispose can throw an ObjectDisposedException when resources are already disposed.

因此,如果多次调用Dispose除第一次调用之外没有其他效果,则只需确保您不会同时调用它们.这绝对是呼叫者的责任.

So if calling Dispose multiple times has no effect other than the first time it's called you only have to ensure that you don't call them at the same time. And that should absolutely be the responsibility of the caller.

Stephen Cleary在CodeProject上写了一篇有关如何实现IDisposable 的文章,我认为非常有帮助的可能问题.

Stephen Cleary wrote an article on CodeProject about how to implement IDisposable and the possible problems which I find extremely helpful.

这篇关于线程安全一次性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆