COM object that has been separated from its underlying RCW can not be used - why does it happen?

后端 未结 2 972
囚心锁ツ
囚心锁ツ 2020-12-11 07:14

I sometimes get the following exception: COM object that has been separated from its underlying RCW can not be used

Sample code:

using (AdOrganiza         


        
相关标签:
2条回答
  • 2020-12-11 07:46

    It seems that the problem is caused by creating DirectoryEntry from NativeObject in AdUser. When I changed AdUser from:

    public class AdUser : DirectoryEntry 
    { 
    public AdUser(DirectoryEntry entry) 
    : base(entry.NativeObject) 
    { 
    } 
    } 
    

    And created wrapper that treats DirectoryEntry as a component:

    public class ActiveDirectoryObject : IDisposable 
    { 
    private bool disposed; 
    public DirectoryEntry Entry { get; protected set; } 
    
    public ActiveDirectoryObject(DirectoryEntry entry) 
    { 
    Entry = entry; 
    } 
    
    public void CommitChanges() 
    { 
    Entry.CommitChanges(); 
    } 
    
    public void Dispose() 
    { 
    Dispose(true); 
    GC.SuppressFinalize(this); 
    } 
    
    private void Dispose(bool disposing) 
    { 
    if (!this.disposed) 
    { 
    if (disposing) 
    { 
    if (Entry != null) Entry.Dispose(); 
    } 
    disposed = true; 
    } 
    } 
    } 
    
    public class AdUser : ActiveDirectoryObject 
    { 
    public AdUser(DirectoryEntry entry) 
    : base(entry) 
    { 
    } 
    } 
    

    Then I don't get these errors. Further details here: http://directoryprogramming.net/forums/thread/7171.aspx

    0 讨论(0)
  • 2020-12-11 07:49

    Yes, it is possible that DirectoryEntry object is disposed due to the garbage collection. GC is running in its own thread, so race on RCW cleanup is possible.

    Try to save reference to it in your AdUser object. I.e. it should looks like

    public class AdUser : DirectoryEntry 
    { 
      DirectoryEntry entry;
        public AdUser(DirectoryEntry entry) : base(entry.NativeObject) 
        { 
          this.entry = entry;
        } 
        ...
    }
    
    0 讨论(0)
提交回复
热议问题