我创建了一个自定义WPF用户控件,供第三方使用.我的控件有一个一次性的私有成员,我想确保一旦包含窗口/应用程序关闭,它的dispose方法将始终被调用.但是,UserControl不是一次性的.我尝试实现IDisposable接口并订阅Unloaded事件,但在主机应用程序关闭时都不会被调用.如果可能的话,我不想依赖我控制的消费者记住调用特定的Dispose方法.
public partial class MyWpfControl : UserControl
{
SomeDisposableObject x;
// where does this code go?
void Somewhere()
{
if (x != null)
{
x.Dispose();
x = null;
}
}
}
Run Code Online (Sandbox Code Playgroud)
到目前为止,我找到的唯一解决方案是订阅Dispatcher的ShutdownStarted事件.这是一种合理的方法吗?
this.Dispatcher.ShutdownStarted += Dispatcher_ShutdownStarted;
Run Code Online (Sandbox Code Playgroud) 我有时会遇到以下异常:无法使用已与其基础RCW分离的COM对象
示例代码:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
AdUser看起来像这样:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的代码的简化版本.有时会出现例外情况,有时则不会.大多数情况下,当我尝试设置UserAccountControl值时会发生这种情况.有谁知道可能是什么原因?
我发现当我处理AdEser创建的DirectoryEntry并且我仍在尝试使用AdUser对象时,会发生此错误.但是,上面发布的代码并非如此.DirectoryEntry可能以某种方式处置自己吗?
当我尝试在许多活动目录对象上执行操作时,我也得到此异常.例如,当我尝试为一千个用户设置SecurityDescriptor时,每200-300个用户就会收到此错误.当我在建立新连接后重试操作时,我不会得到例外.消息是检测到raceonrcwcleanup.我的应用程序不是多线程的.
任何帮助,将不胜感激.