Question

I have often seen code examples of delegate invocation being done as follows:

`

    public delegate void DelegateThreadActivity<T, U> (T sender, U e);

    public event DelegateThreadActivity<Thread, System.EventArgs> OnStart = null;
    public event DelegateThreadActivity<Thread, System.EventArgs> OnStop = null;

    // Helper method for invocation.
    public void RaiseOnStart ()
    {
        DelegateThreadActivity<Thread, System.EventArgs> instance = null;

        try
        {
            instance = this.OnStart;
            // OR
            instance = (DelegateThreadActivity) (object) this.OnStart;

            if (instance != null)
            {
                instance(this, System.EventArgs.Empty);
            }
        }
        catch
        {
        }
    }

`

Why use the [instance] object at all? At first I thought it was corporate convention but have seen seasoned developers do this as well. What is the benefit?

Was it helpful?

Solution

This is done because of thread safety, and prevention of exception raising in the case the delegate turns null.

Consider this code:

if (this.OnStart != null)
{
  this.OnStart(this, System.EventArgs.Empty);
}

Between the execution of the if and the execution of this.OnStart, the OnStart delegate could have been manipulated (possibly changed to null, which would result in an exception).

In the form you provided in your question, a copy of the delegate is made and used when executing. Any change in the original delegate will not be reflected in the copy, which will prevent an exception from coming up. There is a disadvantage with this though: As any changes in the meantime will not be reflected in the copy, which also includes any non-null state, will result in either calling delegates already removed or not calling delegates recently added to it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top