internal bool InternalStart(TaskScheduler scheduler, bool inline, bool throwSchedulerExceptions) { ExecutingTaskScheduler = scheduler; var result = Interlocked.CompareExchange(ref _status, (int)TaskStatus.WaitingForActivation, (int)TaskStatus.Created); if (result != (int)TaskStatus.Created && result != (int)TaskStatus.WaitingForActivation) { return(false); } var didInline = false; try { if (inline) { // Should I worry about this task being a continuation? // WaitAntecedent(CancellationToken); didInline = scheduler.InernalTryExecuteTaskInline(this, IsScheduled); } if (!didInline) { scheduler.QueueTask(this); Interlocked.CompareExchange(ref _status, (int)TaskStatus.WaitingToRun, (int)TaskStatus.WaitingForActivation); } else { PrivateWait(CancellationToken, false); } } catch (ThreadAbortException exception) { if (!didInline) { AddException(exception); FinishThreadAbortedTask(true, false); } } catch (Exception exception) { var taskSchedulerException = new TaskSchedulerException(exception); RecordException(taskSchedulerException); if (throwSchedulerExceptions) { throw taskSchedulerException; } } return(true); }
public bool Wait(int milliseconds, CancellationToken cancellationToken) { if (milliseconds < -1) { throw new ArgumentOutOfRangeException("milliseconds"); } if (milliseconds == -1) { Wait(cancellationToken); return(true); } var start = ThreadingHelper.TicksNow(); do { CancellationCheck(cancellationToken); switch (Status) { case TaskStatus.WaitingForActivation: WaitAntecedent(cancellationToken, milliseconds, start); ExecutingTaskScheduler.InernalTryExecuteTaskInline(this, true); break; case TaskStatus.Created: case TaskStatus.WaitingToRun: case TaskStatus.Running: case TaskStatus.WaitingForChildrenToComplete: var waitHandle = _waitHandle.Value; if (_waitHandle.IsAlive) { waitHandle.Wait ( TimeSpan.FromMilliseconds ( milliseconds - ThreadingHelper.Milliseconds(ThreadingHelper.TicksNow() - start) ), cancellationToken ); } break; case TaskStatus.RanToCompletion: return(true); case TaskStatus.Canceled: ThrowIfExceptional(true); return(true); case TaskStatus.Faulted: ThrowIfExceptional(true); return(true); } } while (ThreadingHelper.Milliseconds(ThreadingHelper.TicksNow() - start) < milliseconds); switch (Status) { case TaskStatus.RanToCompletion: return(true); case TaskStatus.Canceled: ThrowIfExceptional(true); return(true); case TaskStatus.Faulted: ThrowIfExceptional(true); return(true); default: return(false); } }