How would you simplify Entering and Exiting a ReaderWriterLock?

前端 未结 5 696

This seems very noisy to me. Five lines of overhead is just too much.

m_Lock.EnterReadLock()
Try
    Return m_List.Count
Finally
    m_Lock.ExitReadLock()
En         


        
5条回答
  •  离开以前
    2020-12-14 12:19

    I ended up doing this, but I'm still open to better ways or flaws in my design.

    Using m_Lock.ReadSection
        Return m_List.Count
    End Using
    

    This uses this extension method/class:

     Public Function ReadSection(ByVal lock As ReaderWriterLockSlim) As ReadWrapper
        Return New ReadWrapper(lock)
    End Function
    
    
    Public NotInheritable Class ReadWrapper
        Implements IDisposable
    
        Private m_Lock As ReaderWriterLockSlim
        Public Sub New(ByVal lock As ReaderWriterLockSlim)
            m_Lock = lock
            m_Lock.EnterReadLock()
        End Sub
        Public Sub Dispose() Implements IDisposable.Dispose
            m_Lock.ExitReadLock()
        End Sub
    
    End Class
    

提交回复
热议问题