protected static TAsyncResult End()

in src/Fx/AsyncResult.cs [325:370]


        protected static TAsyncResult End<TAsyncResult>(IAsyncResult result)
            where TAsyncResult : AsyncResult
        {
            if (result == null)
            {
                throw new ArgumentNullException(nameof(result));
            }

            TAsyncResult asyncResult = result as TAsyncResult;

            if (asyncResult == null)
            {
                throw new ArgumentException(nameof(result), CommonResources.InvalidAsyncResult);
            }

            if (asyncResult.endCalled)
            {
                throw new InvalidOperationException(CommonResources.AsyncResultAlreadyEnded);
            }

            asyncResult.endCalled = true;

            if (!asyncResult.isCompleted)
            {
                lock (asyncResult.ThisLock)
                {
                    if (!asyncResult.isCompleted && asyncResult.manualResetEvent == null)
                    {
                        asyncResult.manualResetEvent = new ManualResetEvent(asyncResult.isCompleted);
                    }
                }
            }

            if (asyncResult.manualResetEvent != null)
            {
                asyncResult.manualResetEvent.WaitOne();
                asyncResult.manualResetEvent.Dispose();
            }

            if (asyncResult.exception != null)
            {
                ExceptionDispatcher.Throw(asyncResult.exception);
            }

            return asyncResult;
        }