我有一个问题,如何在多线程环境中为异步回调正确添加/删除事件处理程序。
我有 MyCore 类,它接收来自 ProxyDLL 的异步回调,它从非托管代码调度回调。我有订阅事件的表单(托管)。
附加/分离事件的正确方法是什么。我注意到 MulticastDelegate 有 _invocationcount。它能做什么?如果回调调用正在进行直到回调完成,事件的内部逻辑是否会阻止与事件分离?该 puprose 是否存在 _invocationcount?脱离事件(通常)是安全的吗?
class Form1
{
EventHandler m_OnResponse;
Int32 m_SomeValue;
Form1()
{
m_OnResponse = new EventHandler(OnResponseImpl);
m_MyCore.SetCallBackOnLogOn(m_OnResponse);
}
~Form1()
{
m_MyCore.ReleaseCallBackOnLogOn(m_OnResponse);
}
private OnResponseImpl(object sender, EventArgs e)
{
Thread.Sleep(60*1000);
m_SomeValue = 1; // <<-- How to/Who guarantees that Form1 obj is still
// alive. May be callback was invoked earlier and
// we just slept too long
if (!this.IsDisposed)
{
invokeOnFormThread(DoOnResponseImpl, sender, e);
}
}
}
class MyCore
{
private event EventHandler OnLogOn;
public void SetCallBackOnLogOn(EventHandler fn)
{
// lock (OnLogOn)
{
OnLogOn += fn;
}
}
ReleaseCallBackOnLogOn(EventHandler fn)
{
// lock (OnLogOn)
{
OnLogOn -= fn;
}
}
public void DoDispatchOnLogOn()
{
// lock (OnLogOn)
{
if (OnLogOn != null)
{
OnLogOn(this, null);
}
}
}
}