Dispose方法中的线程安全 [英] thread safe in Dispose method

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

问题描述

大家好,

Hello everyone,


这是我的Dispose方法代码.当前,我在考虑是否有必要通过添加锁来防止两个线程同时执行Dispose方法来使其线程安全?


Here is my code for Dispose method. Currently, I am thinking whether it is necessary to make it thread safe by adding a lock to prevent two threads to execute Dispose methods at the same time?

注意:

1. dispose用于指示对Dispose的显式调用或来自Finalizer的隐式调用;

1. disposing is used to indicate explicit call to Dispose or implicit call from Finalizer;

2.用来指示当前实例是否已被处置,以防止再次处置.线程安全考虑因素用于保护此变量.

2. disposed is used to indicate whether current instance is Disposed or not, to prevent from disposing again. The thread safety consideration is used to protect this variable.

代码段

推荐答案

处置从定义上讲不是线程安全的,但实际上取决于它的调用方式.大多数实现都公开了一个公共方法,该方法最终会调用 Dispose (对于文件,请考虑 Close ).在这种情况下,不能保证线程安全,因为多个线程可以同时调用 Close .通过终结器调用Dispose方法时,它是线程安全的,因为它是从终结器线程中调用的.

Dispose is not thread safe by definition but it really depends upon how it is called.  Most implementations expose a public method that eventually calls Dispose (think Close for files).  In this case thread safety is not guaranteed as multiple threads can call Close at the same time.  When the Dispose method is called via the finalizer it is thread safe as it is called from the finalizer thread.

以显示方式实施该方法不是一个好主意.如果从终结器调用该方法,则尤其如此.问题在于,如果从未获得 lock ,则此代码可能会死锁终结器线程.此外,锁定需要引用类型,并且在调用终结器时引用不可用.因此,您的代码比其他任何事情都更容易崩溃.

Implementing the method the way you are showing is a bad idea.  This is especially true if the method is called from the finalizer.  The problem is that this code could deadlock the finalizer thread if the lock was never obtained.  Furthermore lock requires a reference type and references aren't available when the finalizer is called.  Hence your code is morely like to crash than do anything else.

使用原子操作代替锁通常更快,更安全.当您不需要阻止锁时,尤其如此.例如,如果我担心线程安全,这里就是我将如何实现dispose方法的方法.在此示例中,该类是套接字周围的包装器.我在这里也忽略了例外.您可能不想.

It is generally faster, safer to use an atomic operation in lieu of a lock.  This is especially true when you don't want a blocking lock.  For example here is how I would implement a dispose method if I were concerned about thread safety.  In this example the class is a wrapper around a socket.  I'm also ignoring exceptions here.  You might not want to.

代码段


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

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