protected bool TryComplete()

in src/Fx/AsyncResult.cs [114:186]


        protected bool TryComplete(bool didCompleteSynchronously, Exception exception)
        {
            lock (this.ThisLock)
            {
                if (this.isCompleted)
                {
                    return false;
                }

                this.exception = exception;
                this.isCompleted = true;
            }

#if DEBUG
            this.marker.AsyncResult = null;
            this.marker = null;
#endif

            this.completedSynchronously = didCompleteSynchronously;
            if (this.OnCompleting != null)
            {
                // Allow exception replacement, like a catch/throw pattern.
                try
                {
                    this.OnCompleting(this, this.exception);
                }
                catch (Exception e) when (!Fx.IsFatal(e))
                {
                    this.exception = e;
                }
            }

            if (didCompleteSynchronously)
            {
                // If we completedSynchronously, then there's no chance that the manualResetEvent was created so
                // we don't need to worry about a race
                Fx.Assert(this.manualResetEvent == null, "No ManualResetEvent should be created for a synchronous AsyncResult.");
            }
            else
            {
                lock (this.ThisLock)
                {
                    if (this.manualResetEvent != null)
                    {
                        this.manualResetEvent.Set();
                    }
                }
            }

            if (this.callback != null)
            {
                try
                {
                    if (this.VirtualCallback != null)
                    {
                        this.VirtualCallback(this.callback, this);
                    }
                    else
                    {
                        this.callback(this);
                    }
                }
#pragma warning disable 1634
#pragma warning suppress 56500 // transferring exception to another thread
                catch (Exception e) when (!Fx.IsFatal(e))
                {
                    throw new CallbackException(CommonResources.AsyncCallbackThrewException, e);
                }
#pragma warning restore 1634
            }

            return true;
        }