2009-06-23 49 views
1

我有一個類bMainframe,管理連接到4個不同的大型機。它允許以特定方式打開相同的底層非託管庫,並允許同時連接多個主機。每個庫都有自己的非託管大型機連接資源的處理代碼。包裝器也有調用各個主機連接處理代碼的代碼。我可以處理這些非託管資源嗎?而不需要參考每個資源?

如果某人的項目沒有使用全部4個主機,而是在包裝器上調用處置,則會導致錯誤。 (FileLoadException無法加載4個託管主機的程序集X)由於該處理代碼檢查4箇中哪些不是空/空。即使nothing/null導致.net嘗試加載程序集和崩潰。

外包裝中的處理代碼是否有用或必要?有沒有辦法檢查一個類型的程序集是否被加載,但不會觸發net.net來加載類型/程序集?

我修改了下面的代碼來阻止fileloadexception,但我不認爲這是最好的方法。

Protected Overridable Sub Dispose(ByVal disposing As Boolean) 
    If Not Me.disposedValue Then 
     If disposing Then 
      ' TODO: free managed resources when explicitly called 
     End If 
     Try 
      If Me._Linx IsNot Nothing Then 
       If _Linx.cnLinx IsNot Nothing Then 
        Try 
         _Linx.Disconnect() 

        Catch ex As Exception 
         Trace.WriteLine("Error doing linx.disconnectSession") 
        End Try 
        Try 
         _Linx.Dispose() 
        Catch ex As Exception 
         Trace.WriteLine("Error doing linx.dispose") 
        End Try 
       End If 
      End If 
     Catch ex As IO.FileLoadException 
      Debug.WriteLine("Failed to load LinxFile") 
     End Try 
     Try 
      If Me._Acaps IsNot Nothing Then 
       _Acaps.Disconnect() 
       _Acaps.Dispose() 
      End If 
     Catch ex As IO.FileLoadException 
      Debug.WriteLine("Failed to load AcapsFile") 
     End Try 
     Try 
      If Me._Dart IsNot Nothing Then 
       Try 
        _Dart.Dispose() 
       Catch ex As Exception 
        Trace.WriteLine("Error disposing of Dart") 
       End Try 
      End If 
     Catch ex As IO.FileLoadException 
      Debug.WriteLine("Failed to load DartFile") 
     End Try 
     Try 
      If LpsOpen Then 
       Try 
        _Lps.Dispose() 
       Catch ex As Exception 
        Trace.WriteLine("Error disposing of Lps") 
       End Try 
      End If 
     Catch ex As IO.FileLoadException 
      Debug.WriteLine("Failed to load LpsFile") 
     End Try 

     ' TODO: free shared unmanaged resources 
    End If 
    Me.disposedValue = True 
End Sub 

回答

0

這也許可以有四個單獨的類從基類繼承,將有略微不同的實現來處理在他們的dispose函數中......然後你可以遍歷一個數組並在全部使用它們的情況下,如果你在一些情況下使用多個數組。由於您在設計時瞭解不同的大型機,因此必須弄清楚在此特定用途中運行時包含的資源是不正確的。另外,在你釋放垃圾回收器拾取的對象之後,運行GC.Collect()以便垃圾回收器立即運行可能是一個好主意。