引发线程事件时无法访问已处置的对象
Cannot access a disposed object when raising a threaded event
我正在编写的 class 正在使用多线程,我有为我的 class 创建的扩展方法,以线程安全的方式引发事件。
static class MultiThreadHelper
{
public static object Raise(this MulticastDelegate eventToRaise, object sender, EventArgs e)
{
object retVal = null;
MulticastDelegate threadSafeMulticastDelegate = eventToRaise;
if (threadSafeMulticastDelegate != null)
{
foreach (Delegate d in threadSafeMulticastDelegate.GetInvocationList())
{
var synchronizeInvoke = d.Target as ISynchronizeInvoke;
if ((synchronizeInvoke != null) && synchronizeInvoke.InvokeRequired)
{
retVal = synchronizeInvoke.EndInvoke(synchronizeInvoke.BeginInvoke(d, new[] { sender, e }));
}
else
{
retVal = d.DynamicInvoke(new[] { sender, e });
}
}
}
//Return the value of the event invocation or null if none.
return retVal;
}
}
当我的表单试图关闭一个延迟线程时,它仍在尝试返回报告,它引发了一个不再有处理程序的事件。
我最终收到以下错误...
在那行错误发生之前,我可以运行做什么样的检查?还有什么我可以做的或我可以采取不同的方法来解决这个问题吗?
我的第一个想法是 ManifestBuilder
在关闭时没有取消订阅委托。确保使用 -=
语法取消订阅。
我正在编写的 class 正在使用多线程,我有为我的 class 创建的扩展方法,以线程安全的方式引发事件。
static class MultiThreadHelper
{
public static object Raise(this MulticastDelegate eventToRaise, object sender, EventArgs e)
{
object retVal = null;
MulticastDelegate threadSafeMulticastDelegate = eventToRaise;
if (threadSafeMulticastDelegate != null)
{
foreach (Delegate d in threadSafeMulticastDelegate.GetInvocationList())
{
var synchronizeInvoke = d.Target as ISynchronizeInvoke;
if ((synchronizeInvoke != null) && synchronizeInvoke.InvokeRequired)
{
retVal = synchronizeInvoke.EndInvoke(synchronizeInvoke.BeginInvoke(d, new[] { sender, e }));
}
else
{
retVal = d.DynamicInvoke(new[] { sender, e });
}
}
}
//Return the value of the event invocation or null if none.
return retVal;
}
}
当我的表单试图关闭一个延迟线程时,它仍在尝试返回报告,它引发了一个不再有处理程序的事件。
我最终收到以下错误...
在那行错误发生之前,我可以运行做什么样的检查?还有什么我可以做的或我可以采取不同的方法来解决这个问题吗?
我的第一个想法是 ManifestBuilder
在关闭时没有取消订阅委托。确保使用 -=
语法取消订阅。