开发者_运维问答I have an event
this._sequencer.Completed
Two delegates are subscribed to this
this._sequencer.Completed += OnActivityFinished;
this._sequencer.Completed += OnCarrierReLoaded;
The delegates implemnetation is as given below
void OnActivityFinished(object sender, EventArgs e)
{
// Do some activity
this._sequencer.Completed -= OnActivityFinished
}
void OnCarrierReLoaded(object sender, EventArgs e)
{
// Do some activity
this._sequencer.Completed -= OnCarrierReLoaded
}
The delegates in the event are invoked asynchronosly as given below.Will it cause a synchroniztion issue if the delegate is removed from the event as given above? Please help me
void EventHelper::FireAndForget(Delegate^ d, ... array<Object^>^ args)
{
try
{
if (d != nullptr)
{
array<Delegate^>^ delegates = d->GetInvocationList();
for each(Delegate^ delegateMethod in delegates)
{
try
{
DynamicInvokeAsyncProc^ evtDelegate = gcnew DynamicInvokeAsyncProc(this, &EventHelper::OnTriggerEvent);
evtDelegate->BeginInvoke(delegateMethod, args, _dynamicAsyncResult, nullptr); //FIX_DEC_09 Handle Leak
}
catch (Exception^ ex)
{
}
}
}
else
{
}
}
catch (Exception^ e)
{
}
}
void EventHelper::OnTriggerEvent(Delegate^ delegateMethod, array<Object^>^ args)
{
try
{
// Dynamically invokes (late-bound) the method represented by the current delegate.
delegateMethod->DynamicInvoke(args);
}
catch (Exception^ ex)
{
Log(LogMessageType::Error, "EventHelper.OnTriggerEvent", ex->ToString());
}
}
Yes, absolutely, this is not safe. If the threadpool is busy, it can take seconds before the delegate target will start running. The second call to FireAndForget can easily run, say, OnActivityFinished again because the delegate call got scheduled before the 1st one completed. The race is there even if the TP isn't busy and you call FaF frequently. There is no easy way to avoid the race that I see.
精彩评论