A COM object that has been separated from its base RCW cannot be used - why is this happening?

Sometimes I get the following exception: a COM object that has been separated from its base RCW cannot be used

Code example:

using (AdOrganizationalUnit organizationalUnit = new AdOrganizationalUnit(ADHelper.GetDirectoryEntry(ouAdDn))) 
{ 
using (AdUser user = organizationalUnit.AddUser(commonName)) 
{ 
//set some properties 
user.Properties[key].Add(value); 

user.CommitChanges(); 

user.SetPassword(password); //it is set using Invoke 

//must be set after creating user 
user.Properties["UserAccountControl"].Value = 512; 

user.CommitChanges(); 

} 
} 

AdUser is as follows:

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

public bool SetPassword(string password) 
{ 
object result = this.Invoke("SetPassword", new object[] { password }); 
return true; 
} 
} 

This is a simplified version of my code. Sometimes an exception occurs, sometimes not. In most cases, this happens when I try to set the UserAccountControl value. Does anyone know what the reason is?

I found out that this error occurs when I install the DirectoryEntry with which AdUser was created, and I'm still trying to use the AdUser object. However, this is not the case in the code above. Is it possible that DirectoryEntry somehow disposes?

, . , SecurityDescriptor , 200-300 . , . raceonrcwcleanup. .

.

+5
2

, DirectoryEntry NativeObject AdUser. AdUser :

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

, DirectoryEntry :

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) 
{ 
} 
} 

. : http://directoryprogramming.net/forums/thread/7171.aspx

+2

, , DirectoryEntry - . GC , RCW-.

AdUser.

public class AdUser : DirectoryEntry 
{ 
  DirectoryEntry entry;
    public AdUser(DirectoryEntry entry) : base(entry.NativeObject) 
    { 
      this.entry = entry;
    } 
    ...
}
+3

All Articles