예제 #1
0
        public async Task Start(IEnumerable<Task> tasks, CancellationTokenSource cancelSource)
        {
            if (tasks == null) throw new ArgumentNullException(nameof(tasks));
            if (cancelSource == null) throw new ArgumentNullException(nameof(cancelSource));

            while (true)
            {
                var task = _task;
                if (task != null)
                    await Stop().ConfigureAwait(false);

                using (await _lock.LockAsync().ConfigureAwait(false))
                {
                    _cancelSource = cancelSource;

                    if (_task != null)
                        continue; //Another thread sneaked in and started this manager before we got a lock, loop and try again

                    _stopReason = null;
                    WasStopExpected = false;

                    Task[] tasksArray = tasks.ToArray();

                    _task = Task.Run(async () =>
                    {
                        if (tasksArray.Length > 0)
                        {
                            Task<Task> anyTask = tasksArray.Length > 0 ? Task.WhenAny(tasksArray) : null;
                            Task allTasks = tasksArray.Length > 0 ? Task.WhenAll(tasksArray) : null;
                            //Wait for the first task to stop or error
                            Task firstTask = await anyTask.ConfigureAwait(false);

                            //Signal the rest of the tasks to stop
                            if (firstTask.Exception != null)
                                await SignalError(firstTask.Exception).ConfigureAwait(false);
                            else if (StopOnCompletion) //Unless we allow for natural completions
                                await SignalStop().ConfigureAwait(false);

                            //Wait for the other tasks, and signal their errors too just in case
                            try { await allTasks.ConfigureAwait(false); }
                            catch (AggregateException ex) { await SignalError(ex.InnerExceptions.First()).ConfigureAwait(false); }
                            catch (Exception ex) { await SignalError(ex).ConfigureAwait(false); }
                        }

                        if (!StopOnCompletion && !_cancelSource.IsCancellationRequested)
                        {
                            try { await Task.Delay(-1, _cancelSource.Token).ConfigureAwait(false); } //Pause until TaskManager is stopped
                            catch (OperationCanceledException) { }
                        }

                        //Run the cleanup function within our lock
                        if (_stopAction != null)
                            await _stopAction().ConfigureAwait(false);
                        _task = null;
                        _cancelSource = null;
                    });
                    return;
                }
            }
        }
예제 #2
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ExceptionContext"/> class using the values provided.
        /// </summary>
        /// <param name="exceptionInfo">The exception caught.</param>
        /// <param name="catchBlock">The catch block where the exception was caught.</param>
        /// <param name="context">The context in which the exception occurred.</param>
        public ExceptionContext(ExceptionDispatchInfo exceptionInfo, ExceptionContextCatchBlock catchBlock, CommandHandlerContext context)
        {
            if (exceptionInfo == null)
            {
                throw new ArgumentNullException("exceptionInfo");
            }

            this.ExceptionInfo = exceptionInfo;

            if (catchBlock == null)
            {
                throw new ArgumentNullException("catchBlock");
            }

            this.CatchBlock = catchBlock;

            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            this.Context = context;

            CommandHandlerRequest request = context.Request;

            if (request == null)
            {
                throw Error.ArgumentNull(Resources.TypePropertyMustNotBeNull, typeof(HandlerRequest).Name, "Request", "context");
            }

            this.Request = request;
        }
예제 #3
0
 public WinRTFileSystemObject(string fullPath, bool asDirectory)
 {
     _asDirectory = asDirectory;
     _fullPath = fullPath;
     _item = null;
     _initializationException = null;
 }
        public async Task OnTimeoutExceptionAsync(ExceptionDispatchInfo exceptionInfo, TimeSpan timeoutGracePeriod)
        {
            FunctionTimeoutException timeoutException = exceptionInfo.SourceException as FunctionTimeoutException;

            if (timeoutException?.Task != null)
            {
                // We may double the timeoutGracePeriod here by first waiting to see if the iniital
                // function task that started the exception has completed.
                Task completedTask = await Task.WhenAny(timeoutException.Task, Task.Delay(timeoutGracePeriod));

                // If the function task has completed, simply return. The host has already logged the timeout.
                if (completedTask == timeoutException.Task)
                {
                    return;
                }
            }

            LogErrorAndFlush("A function timeout has occurred. Host is shutting down.", exceptionInfo.SourceException);

            // We can't wait on this as it may cause a deadlock if the timeout was fired
            // by a Listener that cannot stop until it has completed.
            Task ignoreTask = _manager.StopAsync();

            // Give the manager and all running tasks some time to shut down gracefully.
            await Task.Delay(timeoutGracePeriod);

            HostingEnvironment.InitiateShutdown();
        }
예제 #5
0
 internal void SignalFailure(ExceptionDispatchInfo error)
 {
     if (_storedException == null)
     {
         _storedException = error;
     }
     SignalComplete();
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="CommandHandlerExecutedContext"/> class.
        /// </summary>
        /// <param name="handlerContext">Then handler context.</param>
        /// <param name="exceptionInfo">The <see cref="ExceptionDispatchInfo"/>. Optionnal.</param>
        public CommandHandlerExecutedContext(CommandHandlerContext handlerContext, ExceptionDispatchInfo exceptionInfo)
        {
            if (handlerContext == null)
            {
                throw Error.ArgumentNull("handlerContext");
            }

            this.ExceptionInfo = exceptionInfo;
            this.handlerContext = handlerContext;
        }
예제 #7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="EventHandlerOccurredContext"/> class.
        /// </summary>
        /// <param name="handlerContext">Then handler context.</param>
        /// <param name="exceptionInfo">The <see cref="ExceptionDispatchInfo"/>. Optionnal.</param>
        public EventHandlerOccurredContext(EventHandlerContext handlerContext, ExceptionDispatchInfo exceptionInfo)
        {
            if (handlerContext == null)
            {
                throw Error.ArgumentNull("handlerContext");
            }

            this.handlerContext = handlerContext;
            this.ExceptionInfo = exceptionInfo;
        }
        internal HttpRouteExceptionHandler(ExceptionDispatchInfo exceptionInfo,
            IExceptionLogger exceptionLogger, IExceptionHandler exceptionHandler)
        {
            Contract.Assert(exceptionInfo != null);
            Contract.Assert(exceptionLogger != null);
            Contract.Assert(exceptionHandler != null);

            _exceptionInfo = exceptionInfo;
            _exceptionLogger = exceptionLogger;
            _exceptionHandler = exceptionHandler;
        }
        public void Throw(ExceptionDispatchInfo exceptionInfo)
        {
            Debug.Assert(exceptionInfo != null);

            Thread thread = new Thread(() =>
            {
                exceptionInfo.Throw();
            });
            thread.Start();
            thread.Join();
        }
예제 #10
0
		public void SetException (AggregateException exception)
		{
#if NET_4_5			
			if (dispatchInfo == null) {
				//
				// Used by task awaiter to rethrow an exception with original call stack, it's
				// needed for first exception only
				//
				dispatchInfo = ExceptionDispatchInfo.Capture (exception.InnerException);
			}
#endif
			this.exception = exception;
		}
예제 #11
0
        public async Task Start(IEnumerable<Task> tasks, CancellationTokenSource cancelSource)
        {
            while (true)
            {
                var task = _task;
                if (task != null)
                    await Stop().ConfigureAwait(false);

                using (await _lock.LockAsync().ConfigureAwait(false))
                {
                    _cancelSource = cancelSource;

                    if (_task != null)
                        continue; //Another thread sneaked in and started this manager before we got a lock, loop and try again

                    _stopReason = null;
                    _wasStopExpected = false;

                    Task[] tasksArray = tasks.ToArray();
                    Task<Task> anyTask = Task.WhenAny(tasksArray);
                    Task allTasks = Task.WhenAll(tasksArray);

                    _task = Task.Run(async () =>
                    {
                        //Wait for the first task to stop or error
                        Task firstTask = await anyTask.ConfigureAwait(false);

                        //Signal the rest of the tasks to stop
                        if (firstTask.Exception != null)
                            await SignalError(firstTask.Exception).ConfigureAwait(false);
                        else
                            await SignalStop().ConfigureAwait(false);

                        //Wait for the other tasks, and signal their errors too just in case
                        try { await allTasks.ConfigureAwait(false); }
                        catch (AggregateException ex) { await SignalError(ex.InnerExceptions.First()).ConfigureAwait(false); } 
                        catch (Exception ex) { await SignalError(ex).ConfigureAwait(false); }

                        //Run the cleanup function within our lock
                        if (_stopAction != null)
                            await _stopAction().ConfigureAwait(false);
                        _task = null;
                        _cancelSource = null;
                    });
                    return;
                }
            }
        }
 private void CallCallbackPossiblyUnderLock(SendOrPostCallback callback, Object state) {
     ThreadContext threadContext = null;
     try {
         threadContext = _application.OnThreadEnter();
         try {
             callback(state);
         }
         catch (Exception e) {
             _error = ExceptionDispatchInfo.Capture(e);
         }
     }
     finally {
         if (threadContext != null) {
             threadContext.DisassociateFromCurrentThread();
         }
     }
 }
예제 #13
0
 private static void ThrowEntryPoint()
 {
     if (s_EDI == null)
     {
         try
         {
             ThrowEntryPointInner();
         }
         catch(Exception ex)
         {
             Console.WriteLine("Caught exception with message: {0}", ex.Message);
             s_EDI = ExceptionDispatchInfo.Capture(ex);
         }
     }
     else
     {
         Console.WriteLine("s_Exception is not null!");
         s_EDI = null;
     }
 }
        protected internal StreamOperationAsyncResult(IAsyncInfo asyncStreamOperation,
                                                      AsyncCallback userCompletionCallback, Object userAsyncStateInfo,
                                                      bool processCompletedOperationInCallback)
        {
            if (asyncStreamOperation == null)
                throw new ArgumentNullException("asyncReadOperation");

            _userCompletionCallback = userCompletionCallback;
            _userAsyncStateInfo = userAsyncStateInfo;

            _asyncStreamOperation = asyncStreamOperation;

            _completed = false;
            _callbackInvoked = false;

            _bytesCompleted = 0;

            _errorInfo = null;

            _processCompletedOperationInCallback = processCompletedOperationInCallback;
        }
        private async Task CheckRetryForExceptionAsync(ExceptionDispatchInfo ex, bool reinitialize)
        {
            if (simulator.AsyncRetryHandler == null)
            {
                // Simply rethrow the exception.
                ex.Throw();
            }
            else
            {
                // Need to release active keys etc.
                CancelActiveInteractions();

                bool result = await simulator.AsyncRetryHandler(ex);
                if (!result)
                    throw new SimulatorCanceledException();

                // When trying again, we need to re-initialize.
                if (reinitialize)
                    await InitializeAsync();
            }
        }
예제 #16
0
    private static bool Scenario1()
    {
        s_EDI = null;

        Console.WriteLine("\nScenario1");
        Thread t1 = new Thread(new ThreadStart(ThrowEntryPoint));
        t1.Start();
        t1.Join();
        
        bool fPassed = false;
        if (s_EDI == null)
        {
            Console.WriteLine("s_EDI shouldn't be null!");
            goto exit;
        }
        
        // ThrowAndCatch the exception
        try
        {
            s_EDI.Throw();
        }
        catch(Exception ex)
        {
            string stackTrace = ex.StackTrace;
            if (stackTrace.IndexOf("ThrowEntryPoint") == -1)
            {
                Console.WriteLine("FAILED - unable to find expected stackTrace");
            }
            else
            {
                Console.WriteLine("Caught: {0}", ex.ToString());
                Console.WriteLine("Passed");
                fPassed = true;
            }
        }
exit:   
        Console.WriteLine("");
        return fPassed;
    }
예제 #17
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ExceptionContext"/> class using the values provided.
        /// </summary>
        /// <param name="exceptionInfo">The exception caught.</param>
        /// <param name="catchBlock">The catch block where the exception was caught.</param>
        /// <param name="request">The request being processed when the exception was caught.</param>
        public ExceptionContext(ExceptionDispatchInfo exceptionInfo, ExceptionContextCatchBlock catchBlock, CommandHandlerRequest request)
        {
            if (exceptionInfo == null)
            {
                throw new ArgumentNullException("exceptionInfo");
            }

            this.ExceptionInfo = exceptionInfo;

            if (catchBlock == null)
            {
                throw new ArgumentNullException("catchBlock");
            }

            this.CatchBlock = catchBlock;

            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            this.Request = request;
        }
예제 #18
0
            /// <summary>
            /// Enqueues the function to be executed and executes all resulting continuations until it is completely done
            /// </summary>
            public void Run()
            {
                Post(async _ =>
                {
                    try
                    {
                        await _task();
                    }
                    catch (Exception exception)
                    {
                        _caughtException = ExceptionDispatchInfo.Capture(exception);
                        throw;
                    }
                    finally
                    {
                        Post(state => _done = true, null);
                    }
                }, null);

                while (!_done)
                {
                    Tuple<SendOrPostCallback, object> task;

                    if (_items.TryDequeue(out task))
                    {
                        task.Item1(task.Item2);

                        if (_caughtException == null) continue;

                        _caughtException.Throw();
                    }
                    else
                    {
                        _workItemsWaiting.WaitOne();
                    }
                }
            }
 public async Task CheckRetryForExceptionAsync(ExceptionDispatchInfo ex) =>
     await CheckRetryForExceptionAsync(ex, true);
 public void Reset() {
     // All processors see the _error field write as being no later than the _asyncState field write.
     _error = null;
     _asyncState = ASYNC_STATE_NONE;
 }
 public void ReportError() {
     // Using ExceptionDispatchInfo preserves the Exception's stack trace when rethrowing.
     ExceptionDispatchInfo error = _error;
     if (error != null) {
         _error = null; // prevent long-lived Exception objects on the heap
         error.Throw();
     }
 }
            // Invoked from the callback to signal that the End* method has run to completion.
            // Returns 'true' if the current thread should call ResumeSteps, 'false' if not.
            public bool RegisterAsyncCompletion(Exception error) {
                // Before the call to Exchange below, the _asyncCompletionInfo field will have the value
                // ASYNC_STATE_NONE or ASYNC_STATE_BEGIN_UNWOUND. If it's the former, then the Begin* method
                // hasn't yet returned control to IExecutionStep.Execute. From this step's point of view,
                // this can be treated as a synchronous completion, which will allow us to call ResumeSteps
                // on the original thread and save the cost of destroying  the existing ThreadContext and
                // creating a new one. If the original value is instead ASYNC_STATE_BEGIN_UNWOUND, then
                // the Begin* method already returned control to IExecutionStep.Execute and this step was
                // marked as having an asynchronous completion. The original thread will tear down the
                // ThreadContext, so the current thread should call back into ResumeSteps to resurrect it.
                //
                // If there was an error, we'll use the _error field to store it so that IExecutionStep.Execute
                // can rethrow it as it's unwinding.

                // Interlocked performs a volatile write; all processors will see the write to _error as being
                // no later than the write to _asyncState.
                _error = (error != null) ? ExceptionDispatchInfo.Capture(error) : null;
                int originalState = Interlocked.Exchange(ref _asyncState, ASYNC_STATE_CALLBACK_COMPLETED);
                if (originalState == ASYNC_STATE_NONE) {
                    return false; // IExecutionStep.Execute should call ResumeSteps
                }

                Debug.Assert(originalState == ASYNC_STATE_BEGIN_UNWOUND, "Unexpected state.");
                _error = null; // to prevent long-lived exception object; write doesn't need to be volatile since nobody reads this field anyway in this case
                return true; // this thread should call ResumeSteps
            }
예제 #23
0
파일: SslState.cs 프로젝트: eerhardt/corefx
        //
        //  This is to reset auth state on remote side.
        //  If this write succeeds we will allow auth retrying.
        //
        private void StartSendAuthResetSignal(ProtocolToken message, AsyncProtocolRequest asyncRequest, ExceptionDispatchInfo exception)
        {
            if (message == null || message.Size == 0)
            {
                //
                // We don't have an alert to send so cannot retry and fail prematurely.
                //
                exception.Throw();
            }

            if (asyncRequest == null)
            {
                InnerStream.Write(message.Payload, 0, message.Size);
            }
            else
            {
                asyncRequest.AsyncState = exception;
                IAsyncResult ar = InnerStreamAPM.BeginWrite(message.Payload, 0, message.Size, s_writeCallback, asyncRequest);
                if (!ar.CompletedSynchronously)
                {
                    return;
                }
                InnerStreamAPM.EndWrite(ar);
            }

            exception.Throw();
        }
예제 #24
0
파일: SslState.cs 프로젝트: eerhardt/corefx
        internal void ValidateCreateContext(bool isServer, string targetHost, SslProtocols enabledSslProtocols, X509Certificate serverCertificate, X509CertificateCollection clientCertificates, bool remoteCertRequired, bool checkCertRevocationStatus, bool checkCertName)
        {
            //
            // We don't support SSL alerts right now, hence any exception is fatal and cannot be retried.
            //
            if (_exception != null)
            {
                _exception.Throw();
            }

            if (Context != null && Context.IsValidContext)
            {
                throw new InvalidOperationException(SR.net_auth_reauth);
            }

            if (Context != null && IsServer != isServer)
            {
                throw new InvalidOperationException(SR.net_auth_client_server);
            }

            if (targetHost == null)
            {
                throw new ArgumentNullException(nameof(targetHost));
            }

            if (isServer && serverCertificate == null)
            {
                throw new ArgumentNullException(nameof(serverCertificate));
            }

            if ((int)enabledSslProtocols == 0)
            {
                throw new ArgumentException(SR.Format(SR.net_invalid_enum, "SslProtocolType"), "sslProtocolType");
            }

            if (clientCertificates == null)
            {
                clientCertificates = new X509CertificateCollection();
            }

            if (targetHost.Length == 0)
            {
                targetHost = "?" + Interlocked.Increment(ref s_uniqueNameInteger).ToString(NumberFormatInfo.InvariantInfo);
            }

            _exception = null;
            try
            {
                _context = new SecureChannel(targetHost, isServer, enabledSslProtocols, serverCertificate, clientCertificates, remoteCertRequired,
                                                                 checkCertName, checkCertRevocationStatus, _encryptionPolicy, _certSelectionDelegate);
            }
            catch (Win32Exception e)
            {
                throw new AuthenticationException(SR.net_auth_SSPI, e);
            }
        }
예제 #25
0
파일: SslState.cs 프로젝트: eerhardt/corefx
 //
 // This is to not depend on GC&SafeHandle class if the context is not needed anymore.
 //
 internal void Close()
 {
     _exception = ExceptionDispatchInfo.Capture(new ObjectDisposedException("SslStream"));
     if (Context != null)
     {
         Context.Close();
     }
 }
예제 #26
0
 private static void SetCustomLoaderFailure(string appId, ExceptionDispatchInfo error) {
     _customLoaderStartupError = new KeyValuePair<string, ExceptionDispatchInfo>(appId, error);
 }
예제 #27
0
 internal LazyException(Exception exception, LazyThreadSafetyMode mode)
 {
     m_exceptionInfo = System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(exception);
     m_mode          = mode;
 }
예제 #28
0
        /// <summary>Sets the cancellation exception.</summary>
        /// <param name="exceptionObject">The cancellation exception.</param>
        /// <remarks>
        /// Must be called under lock.
        /// </remarks>
        private void SetCancellationException(object exceptionObject)
        {
            Contract.Requires(exceptionObject != null, "Expected exceptionObject to be non-null.");

            Debug.Assert(m_cancellationException == null,
                "Expected SetCancellationException to be called only once.");
            // Breaking this assumption will overwrite a previously OCE,
            // and implies something may be wrong elsewhere, since there should only ever be one.

            Debug.Assert(m_faultExceptions == null,
                "Expected SetCancellationException to be called before any faults were added.");
            // Breaking this assumption shouldn't hurt anything here, but it implies something may be wrong elsewhere.
            // If this changes, make sure to only conditionally mark as handled below.

            // Store the cancellation exception
            var oce = exceptionObject as OperationCanceledException;
            if (oce != null)
            {
                m_cancellationException = ExceptionDispatchInfo.Capture(oce);
            }
            else
            {
                var edi = exceptionObject as ExceptionDispatchInfo;
                Debug.Assert(edi != null && edi.SourceException is OperationCanceledException,
                    "Expected an OCE or an EDI that contained an OCE");
                m_cancellationException = edi;
            }

            // This is just cancellation, and there are no faults, so mark the holder as handled.
            MarkAsHandled(false);
        }
 private static HttpRouteExceptionHandler CreateProductUnderTest(ExceptionDispatchInfo exceptionInfo)
 {
     return new HttpRouteExceptionHandler(exceptionInfo);
 }
 private static HttpRouteExceptionHandler CreateProductUnderTest(ExceptionDispatchInfo exceptionInfo,
     IExceptionLogger exceptionLogger, IExceptionHandler exceptionHandler)
 {
     return new HttpRouteExceptionHandler(exceptionInfo, exceptionLogger, exceptionHandler);
 }
예제 #31
-1
        private IntPtr AllocException(Exception ex)
        {
            _lastException = ExceptionDispatchInfo.Capture(ex);

            string exString = ex.ToString();
            IntPtr nativeException = AllocException(exString, exString.Length);
            if (_nativeExceptions == null)
            {
                _nativeExceptions = new List<IntPtr>();
            }
            _nativeExceptions.Add(nativeException);
            return nativeException;
        }