How to fix a CA2000 IDisposable C# compiler warning, when using a global cache

后端 未结 3 1191
醉梦人生
醉梦人生 2020-12-20 20:37

CA2000 is a warning regarding the IDisposable interface:

CA2000 : Microsoft.Reliability : In method \'ImportProcessor.GetContext(string)\', call Sys

3条回答
  •  -上瘾入骨i
    2020-12-20 21:19

    Michael's solution does not seem to work when converted to VB.Net. The following two functions were tested under VS 2017:

        Public Function OpenStream(ByVal filePathName As String) As System.IO.FileStream
            Dim fileStream As System.IO.FileStream = Nothing
            Dim tempFileStream As System.IO.FileStream = Nothing
            If Not String.IsNullOrWhiteSpace(filePathName) Then
                Try
                    tempFileStream = New System.IO.FileStream(filePathName, System.IO.FileMode.Open, System.IO.FileAccess.Read)
                    fileStream = tempFileStream
                Catch
                    tempFileStream?.Dispose()
                    Throw
                End Try
            End If
            Return fileStream
        End Function
    
        Public Function OpenReader(ByVal filePathName As String) As System.IO.BinaryReader
            If String.IsNullOrWhiteSpace(filePathName) Then Throw New ArgumentNullException(NameOf(filePathName))
            If Not System.IO.File.Exists(filePathName) Then Throw New System.IO.FileNotFoundException("Failed opening a binary reader -- file not found.", filePathName)
            Dim tempReader As System.IO.BinaryReader = Nothing
            Dim reader As System.IO.BinaryReader = Nothing
            Dim stream As IO.FileStream = Nothing
            Try
                stream = Methods.OpenStream(filePathName)
                tempReader = New System.IO.BinaryReader(stream)
                reader = tempReader
            Catch
                stream?.Dispose()
                tempReader?.Dispose()
                Throw
            End Try
            Return reader
        End Function
    

提交回复
热议问题