protected bool TryComplete()

in iothub/device/src/Common/AsyncResult.cs [99:176]


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

                _exception = exception;
                IsCompleted = true;
            }

#if DEBUG
            _marker.AsyncResult = null;
            _marker = null;
#endif

            CompletedSynchronously = didCompleteSynchronously;
            if (OnCompleting != null)
            {
                // Allow exception replacement, like a catch/throw pattern.
                try
                {
                    OnCompleting(this, _exception);
                }
                catch (Exception e) when (!Fx.IsFatal(e))
                {
                    _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(_manualResetEvent == null, "No ManualResetEvent should be created for a synchronous AsyncResult.");
            }
            else
            {
                lock (ThisLock)
                {
                    if (_manualResetEvent != null)
                    {
                        _manualResetEvent.Set();
                    }
                }
            }

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

                    throw Fx.Exception.AsError(new InvalidOperationException(CommonResources.AsyncCallbackThrewException, e));
                }
#pragma warning restore 1634
            }

            return true;
        }