Boxing Style Delegate Call

I often saw examples of delegate delegation code running 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 an object [instance]at all? At first I thought it was a corporate convention, but they also looked after experienced developers. What is the use?

+3
source share
1 answer

This is done due to thread safety and preventing the exception from being thrown if the delegate is turning null.

Consider this code:

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

Between execution ifand execution, the this.OnStartdelegate OnStartcould be processed (possibly changed to null, which will result in an exception).

, , . , . , : , null, , , .

+6

All Articles