diff options
Diffstat (limited to 'src/mscorlib/src/System/Threading/Tasks')
18 files changed, 388 insertions, 586 deletions
diff --git a/src/mscorlib/src/System/Threading/Tasks/AsyncCausalityTracer.cs b/src/mscorlib/src/System/Threading/Tasks/AsyncCausalityTracer.cs index c29b11a922..ec7c5aaeea 100644 --- a/src/mscorlib/src/System/Threading/Tasks/AsyncCausalityTracer.cs +++ b/src/mscorlib/src/System/Threading/Tasks/AsyncCausalityTracer.cs @@ -131,7 +131,6 @@ namespace System.Threading.Tasks private static Loggers f_LoggingOn; //assumes false by default // The precise static constructor will run first time somebody attempts to access this class - [SecuritySafeCritical] static AsyncCausalityTracer() { if (!Environment.IsWinRTSupported) return; @@ -153,7 +152,7 @@ namespace System.Threading.Tasks s_TracerFactory = (WFD.IAsyncCausalityTracerStatics)factory; EventRegistrationToken token = s_TracerFactory.add_TracingStatusChanged(new EventHandler<WFD.TracingStatusChangedEventArgs>(TracingStatusChangedHandler)); - Contract.Assert(token != default(EventRegistrationToken), "EventRegistrationToken is null"); + Debug.Assert(token != default(EventRegistrationToken), "EventRegistrationToken is null"); } catch (Exception ex) { @@ -165,7 +164,6 @@ namespace System.Threading.Tasks } - [SecuritySafeCritical] private static void TracingStatusChangedHandler(Object sender, WFD.TracingStatusChangedEventArgs args) { if (args.Enabled) diff --git a/src/mscorlib/src/System/Threading/Tasks/BeginEndAwaitableAdapter.cs b/src/mscorlib/src/System/Threading/Tasks/BeginEndAwaitableAdapter.cs index 05e6dbf1a9..71eb787c5e 100644 --- a/src/mscorlib/src/System/Threading/Tasks/BeginEndAwaitableAdapter.cs +++ b/src/mscorlib/src/System/Threading/Tasks/BeginEndAwaitableAdapter.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.IO; using System.Runtime.CompilerServices; @@ -62,9 +63,9 @@ internal sealed class BeginEndAwaitableAdapter : ICriticalNotifyCompletion { /// It expects that an BeginEndAwaitableAdapter instance was supplied to the APM Begin method as the object state.</summary> public readonly static AsyncCallback Callback = (asyncResult) => { - Contract.Assert(asyncResult != null); - Contract.Assert(asyncResult.IsCompleted); - Contract.Assert(asyncResult.AsyncState is BeginEndAwaitableAdapter); + Debug.Assert(asyncResult != null); + Debug.Assert(asyncResult.IsCompleted); + Debug.Assert(asyncResult.AsyncState is BeginEndAwaitableAdapter); // Get the adapter object supplied as the "object state" to the Begin method BeginEndAwaitableAdapter adapter = (BeginEndAwaitableAdapter) asyncResult.AsyncState; @@ -81,7 +82,7 @@ internal sealed class BeginEndAwaitableAdapter : ICriticalNotifyCompletion { Action continuation = Interlocked.Exchange(ref adapter._continuation, CALLBACK_RAN); if (continuation != null) { - Contract.Assert(continuation != CALLBACK_RAN); + Debug.Assert(continuation != CALLBACK_RAN); continuation(); } }; @@ -108,10 +109,9 @@ internal sealed class BeginEndAwaitableAdapter : ICriticalNotifyCompletion { /// <summary>Schedules the continuation to run when the operation completes.</summary> /// <param name="continuation">The continuation.</param> - [SecurityCritical] public void UnsafeOnCompleted(Action continuation) { - Contract.Assert(continuation != null); + Debug.Assert(continuation != null); OnCompleted(continuation); } @@ -120,7 +120,7 @@ internal sealed class BeginEndAwaitableAdapter : ICriticalNotifyCompletion { /// <param name="continuation">The continuation.</param> public void OnCompleted(Action continuation) { - Contract.Assert(continuation != null); + Debug.Assert(continuation != null); // If the continuation field is null, then set it to be the target continuation // so that when the operation completes, it'll invoke the continuation. If it's non-null, @@ -139,7 +139,7 @@ internal sealed class BeginEndAwaitableAdapter : ICriticalNotifyCompletion { /// <returns>The IAsyncResult for the operation.</returns> public IAsyncResult GetResult() { - Contract.Assert(_asyncResult != null && _asyncResult.IsCompleted); + Debug.Assert(_asyncResult != null && _asyncResult.IsCompleted); // Get the IAsyncResult IAsyncResult result = _asyncResult; diff --git a/src/mscorlib/src/System/Threading/Tasks/ConcurrentExclusiveSchedulerPair.cs b/src/mscorlib/src/System/Threading/Tasks/ConcurrentExclusiveSchedulerPair.cs index cb4a22bb2b..c7a96b0394 100644 --- a/src/mscorlib/src/System/Threading/Tasks/ConcurrentExclusiveSchedulerPair.cs +++ b/src/mscorlib/src/System/Threading/Tasks/ConcurrentExclusiveSchedulerPair.cs @@ -28,7 +28,6 @@ namespace System.Threading.Tasks /// Provides concurrent and exclusive task schedulers that coordinate to execute /// tasks while ensuring that concurrent tasks may run concurrently and exclusive tasks never do. /// </summary> - [HostProtection(Synchronization = true, ExternalThreading = true)] [DebuggerDisplay("Concurrent={ConcurrentTaskCountForDebugger}, Exclusive={ExclusiveTaskCountForDebugger}, Mode={ModeForDebugger}")] [DebuggerTypeProxy(typeof(ConcurrentExclusiveSchedulerPair.DebugView))] public class ConcurrentExclusiveSchedulerPair @@ -101,9 +100,9 @@ namespace System.Threading.Tasks public ConcurrentExclusiveSchedulerPair(TaskScheduler taskScheduler, int maxConcurrencyLevel, int maxItemsPerTask) { // Validate arguments - if (taskScheduler == null) throw new ArgumentNullException("taskScheduler"); - if (maxConcurrencyLevel == 0 || maxConcurrencyLevel < -1) throw new ArgumentOutOfRangeException("maxConcurrencyLevel"); - if (maxItemsPerTask == 0 || maxItemsPerTask < -1) throw new ArgumentOutOfRangeException("maxItemsPerTask"); + if (taskScheduler == null) throw new ArgumentNullException(nameof(taskScheduler)); + if (maxConcurrencyLevel == 0 || maxConcurrencyLevel < -1) throw new ArgumentOutOfRangeException(nameof(maxConcurrencyLevel)); + if (maxItemsPerTask == 0 || maxItemsPerTask < -1) throw new ArgumentOutOfRangeException(nameof(maxItemsPerTask)); Contract.EndContractBlock(); // Store configuration @@ -213,13 +212,13 @@ namespace System.Threading.Tasks ThreadPool.QueueUserWorkItem(state => { var localCs = (CompletionState)state; // don't use 'cs', as it'll force a closure - Contract.Assert(!localCs.Task.IsCompleted, "Completion should only happen once."); + Debug.Assert(!localCs.Task.IsCompleted, "Completion should only happen once."); var exceptions = localCs.m_exceptions; bool success = (exceptions != null && exceptions.Count > 0) ? localCs.TrySetException(exceptions) : localCs.TrySetResult(default(VoidTaskResult)); - Contract.Assert(success, "Expected to complete completion task."); + Debug.Assert(success, "Expected to complete completion task."); }, cs); } } @@ -336,7 +335,7 @@ namespace System.Threading.Tasks // Check to see if all tasks have completed and if completion has been requested. CleanupStateIfCompletingAndQuiesced(); } - else Contract.Assert(m_processingCount == EXCLUSIVE_PROCESSING_SENTINEL, "The processing count must be the sentinel if it's not >= 0."); + else Debug.Assert(m_processingCount == EXCLUSIVE_PROCESSING_SENTINEL, "The processing count must be the sentinel if it's not >= 0."); } /// <summary> @@ -351,7 +350,7 @@ namespace System.Threading.Tasks try { // Note that we're processing exclusive tasks on the current thread - Contract.Assert(!m_threadProcessingMapping.ContainsKey(Thread.CurrentThread.ManagedThreadId), + Debug.Assert(!m_threadProcessingMapping.ContainsKey(Thread.CurrentThread.ManagedThreadId), "This thread should not yet be involved in this pair's processing."); m_threadProcessingMapping[Thread.CurrentThread.ManagedThreadId] = ProcessingMode.ProcessingExclusiveTask; @@ -372,7 +371,7 @@ namespace System.Threading.Tasks // We're no longer processing exclusive tasks on the current thread ProcessingMode currentMode; m_threadProcessingMapping.TryRemove(Thread.CurrentThread.ManagedThreadId, out currentMode); - Contract.Assert(currentMode == ProcessingMode.ProcessingExclusiveTask, + Debug.Assert(currentMode == ProcessingMode.ProcessingExclusiveTask, "Somehow we ended up escaping exclusive mode."); lock (ValueLock) @@ -382,7 +381,7 @@ namespace System.Threading.Tasks // There might be more concurrent tasks available, for example, if concurrent tasks arrived // after we exited the loop, or if we exited the loop while concurrent tasks were still // available but we hit our maxItemsPerTask limit. - Contract.Assert(m_processingCount == EXCLUSIVE_PROCESSING_SENTINEL, "The processing mode should not have deviated from exclusive."); + Debug.Assert(m_processingCount == EXCLUSIVE_PROCESSING_SENTINEL, "The processing mode should not have deviated from exclusive."); m_processingCount = 0; ProcessAsyncIfNecessary(true); } @@ -400,7 +399,7 @@ namespace System.Threading.Tasks try { // Note that we're processing concurrent tasks on the current thread - Contract.Assert(!m_threadProcessingMapping.ContainsKey(Thread.CurrentThread.ManagedThreadId), + Debug.Assert(!m_threadProcessingMapping.ContainsKey(Thread.CurrentThread.ManagedThreadId), "This thread should not yet be involved in this pair's processing."); m_threadProcessingMapping[Thread.CurrentThread.ManagedThreadId] = ProcessingMode.ProcessingConcurrentTasks; @@ -432,7 +431,7 @@ namespace System.Threading.Tasks // We're no longer processing concurrent tasks on the current thread ProcessingMode currentMode; m_threadProcessingMapping.TryRemove(Thread.CurrentThread.ManagedThreadId, out currentMode); - Contract.Assert(currentMode == ProcessingMode.ProcessingConcurrentTasks, + Debug.Assert(currentMode == ProcessingMode.ProcessingConcurrentTasks, "Somehow we ended up escaping concurrent mode."); lock (ValueLock) @@ -442,7 +441,7 @@ namespace System.Threading.Tasks // There might be more concurrent tasks available, for example, if concurrent tasks arrived // after we exited the loop, or if we exited the loop while concurrent tasks were still // available but we hit our maxItemsPerTask limit. - Contract.Assert(m_processingCount > 0, "The procesing mode should not have deviated from concurrent."); + Debug.Assert(m_processingCount > 0, "The procesing mode should not have deviated from concurrent."); if (m_processingCount > 0) --m_processingCount; ProcessAsyncIfNecessary(true); } @@ -524,10 +523,9 @@ namespace System.Threading.Tasks /// <summary>Queues a task to the scheduler.</summary> /// <param name="task">The task to be queued.</param> - [SecurityCritical] protected internal override void QueueTask(Task task) { - Contract.Assert(task != null, "Infrastructure should have provided a non-null task."); + Debug.Assert(task != null, "Infrastructure should have provided a non-null task."); lock (m_pair.ValueLock) { // If the scheduler has already had completion requested, no new work is allowed to be scheduled @@ -541,10 +539,9 @@ namespace System.Threading.Tasks /// <summary>Executes a task on this scheduler.</summary> /// <param name="task">The task to be executed.</param> - [SecuritySafeCritical] internal void ExecuteTask(Task task) { - Contract.Assert(task != null, "Infrastructure should have provided a non-null task."); + Debug.Assert(task != null, "Infrastructure should have provided a non-null task."); base.TryExecuteTask(task); } @@ -552,10 +549,9 @@ namespace System.Threading.Tasks /// <param name="task">The task to execute.</param> /// <param name="taskWasPreviouslyQueued">Whether the task was previously queued to the scheduler.</param> /// <returns>true if the task could be executed; otherwise, false.</returns> - [SecurityCritical] protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { - Contract.Assert(task != null, "Infrastructure should have provided a non-null task."); + Debug.Assert(task != null, "Infrastructure should have provided a non-null task."); // If the scheduler has had completion requested, no new work is allowed to be scheduled. // A non-locked read on m_completionRequested (in CompletionRequested) is acceptable here because: @@ -628,7 +624,7 @@ namespace System.Threading.Tasks } catch { - Contract.Assert(t.IsFaulted, "Task should be faulted due to the scheduler faulting it and throwing the exception."); + Debug.Assert(t.IsFaulted, "Task should be faulted due to the scheduler faulting it and throwing the exception."); var ignored = t.Exception; throw; } @@ -642,7 +638,6 @@ namespace System.Threading.Tasks /// This method is separated out not because of performance reasons but so that /// the SecuritySafeCritical attribute may be employed. /// </remarks> - [SecuritySafeCritical] private static bool TryExecuteTaskShim(object state) { var tuple = (Tuple<ConcurrentExclusiveTaskScheduler, Task>)state; @@ -651,7 +646,6 @@ namespace System.Threading.Tasks /// <summary>Gets for debugging purposes the tasks scheduled to this scheduler.</summary> /// <returns>An enumerable of the tasks queued.</returns> - [SecurityCritical] protected override IEnumerable<Task> GetScheduledTasks() { return m_tasks; } /// <summary>Gets the number of tasks queued to this scheduler.</summary> @@ -748,11 +742,11 @@ namespace System.Threading.Tasks exceptionThrown = false; } catch (SynchronizationLockException) { exceptionThrown = true; } - Contract.Assert(held == !exceptionThrown, "The locking scheme was not correctly followed."); + Debug.Assert(held == !exceptionThrown, "The locking scheme was not correctly followed."); } #endif #else - Contract.Assert(Monitor.IsEntered(syncObj) == held, "The locking scheme was not correctly followed."); + Debug.Assert(Monitor.IsEntered(syncObj) == held, "The locking scheme was not correctly followed."); #endif } diff --git a/src/mscorlib/src/System/Threading/Tasks/FutureFactory.cs b/src/mscorlib/src/System/Threading/Tasks/FutureFactory.cs index b1f634c707..c98e219e86 100644 --- a/src/mscorlib/src/System/Threading/Tasks/FutureFactory.cs +++ b/src/mscorlib/src/System/Threading/Tasks/FutureFactory.cs @@ -15,6 +15,7 @@ using System.Security; using System.Security.Permissions; using System.Runtime.CompilerServices; using System.Threading; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.Versioning; @@ -38,7 +39,6 @@ namespace System.Threading.Tasks /// <see cref="System.Threading.Tasks.Task{TResult}.Factory">Task{TResult}.Factory</see> property. /// </para> /// </remarks> - [HostProtection(Synchronization = true, ExternalThreading = true)] public class TaskFactory<TResult> { // Member variables, DefaultScheduler, other properties and ctors @@ -832,32 +832,17 @@ namespace System.Threading.Tasks try { - // Do NOT change the code below. - // 4.5 relies on the fact that IAsyncResult CompletedSynchronously flag needs to be set correctly, - // sadly this has not been the case that is why the behaviour from 4.5 broke 4.0 buggy apps. Any other - // change will likely brake 4.5 behavior so if possible never touch this code again. - if (BinaryCompatibility.TargetsAtLeast_Desktop_V4_5) + //This is 4.5 behaviour + //if we don't require synchronization, a faster set result path is taken + var asyncResult = beginMethod(iar => { - //This is 4.5 behaviour - //if we don't require synchronization, a faster set result path is taken - var asyncResult = beginMethod(iar => - { - if (!iar.CompletedSynchronously) - FromAsyncCoreLogic(iar, endFunction, endAction, promise, requiresSynchronization: true); - }, state); - if (asyncResult.CompletedSynchronously) - { - Contract.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed."); - FromAsyncCoreLogic(asyncResult, endFunction, endAction, promise, requiresSynchronization: false); - } - } - else - { - //This is the original 4.0 behaviour - var asyncResult = beginMethod(iar => - { + if (!iar.CompletedSynchronously) FromAsyncCoreLogic(iar, endFunction, endAction, promise, requiresSynchronization: true); - }, state); + }, state); + if (asyncResult.CompletedSynchronously) + { + Debug.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed."); + FromAsyncCoreLogic(asyncResult, endFunction, endAction, promise, requiresSynchronization: false); } } catch @@ -969,31 +954,16 @@ namespace System.Threading.Tasks try { - // Do NOT change the code below. - // 4.5 relies on the fact that IAsyncResult CompletedSynchronously flag needs to be set correctly, - // sadly this has not been the case that is why the behaviour from 4.5 broke 4.0 buggy apps. Any other - // change will likely brake 4.5 behavior so if possible never touch this code again. - if (BinaryCompatibility.TargetsAtLeast_Desktop_V4_5) + //if we don't require synchronization, a faster set result path is taken + var asyncResult = beginMethod(arg1, iar => { - //if we don't require synchronization, a faster set result path is taken - var asyncResult = beginMethod(arg1, iar => - { - if (!iar.CompletedSynchronously) - FromAsyncCoreLogic(iar, endFunction, endAction, promise, requiresSynchronization: true); - }, state); - if (asyncResult.CompletedSynchronously) - { - Contract.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed."); - FromAsyncCoreLogic(asyncResult, endFunction, endAction, promise, requiresSynchronization: false); - } - } - else - { - //quirk for previous versions - var asyncResult = beginMethod(arg1, iar => - { + if (!iar.CompletedSynchronously) FromAsyncCoreLogic(iar, endFunction, endAction, promise, requiresSynchronization: true); - }, state); + }, state); + if (asyncResult.CompletedSynchronously) + { + Debug.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed."); + FromAsyncCoreLogic(asyncResult, endFunction, endAction, promise, requiresSynchronization: false); } } catch @@ -1114,31 +1084,16 @@ namespace System.Threading.Tasks try { - // Do NOT change the code below. - // 4.5 relies on the fact that IAsyncResult CompletedSynchronously flag needs to be set correctly, - // sadly this has not been the case that is why the behaviour from 4.5 broke 4.0 buggy apps. Any other - // change will likely brake 4.5 behavior so if possible never touch this code again. - if (BinaryCompatibility.TargetsAtLeast_Desktop_V4_5) + //if we don't require synchronization, a faster set result path is taken + var asyncResult = beginMethod(arg1, arg2, iar => { - //if we don't require synchronization, a faster set result path is taken - var asyncResult = beginMethod(arg1, arg2, iar => - { - if (!iar.CompletedSynchronously) - FromAsyncCoreLogic(iar, endFunction, endAction, promise, requiresSynchronization: true); - }, state); - if (asyncResult.CompletedSynchronously) - { - Contract.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed."); - FromAsyncCoreLogic(asyncResult, endFunction, endAction, promise, requiresSynchronization: false); - } - } - else - { - //quirk for previous versions - var asyncResult = beginMethod(arg1, arg2, iar => - { + if (!iar.CompletedSynchronously) FromAsyncCoreLogic(iar, endFunction, endAction, promise, requiresSynchronization: true); - }, state); + }, state); + if (asyncResult.CompletedSynchronously) + { + Debug.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed."); + FromAsyncCoreLogic(asyncResult, endFunction, endAction, promise, requiresSynchronization: false); } } catch @@ -1266,31 +1221,16 @@ namespace System.Threading.Tasks try { - // Do NOT change the code below. - // 4.5 relies on the fact that IAsyncResult CompletedSynchronously flag needs to be set correctly, - // sadly this has not been the case that is why the behaviour from 4.5 broke 4.0 buggy apps. Any other - // change will likely brake 4.5 behavior so if possible never touch this code again. - if (BinaryCompatibility.TargetsAtLeast_Desktop_V4_5) + //if we don't require synchronization, a faster set result path is taken + var asyncResult = beginMethod(arg1, arg2, arg3, iar => { - //if we don't require synchronization, a faster set result path is taken - var asyncResult = beginMethod(arg1, arg2, arg3, iar => - { - if (!iar.CompletedSynchronously) - FromAsyncCoreLogic(iar, endFunction, endAction, promise, requiresSynchronization: true); - }, state); - if (asyncResult.CompletedSynchronously) - { - Contract.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed."); - FromAsyncCoreLogic(asyncResult, endFunction, endAction, promise, requiresSynchronization: false); - } - } - else - { - //quirk for previous versions - var asyncResult = beginMethod(arg1, arg2, arg3, iar => - { + if (!iar.CompletedSynchronously) FromAsyncCoreLogic(iar, endFunction, endAction, promise, requiresSynchronization: true); - }, state); + }, state); + if (asyncResult.CompletedSynchronously) + { + Debug.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed."); + FromAsyncCoreLogic(asyncResult, endFunction, endAction, promise, requiresSynchronization: false); } } catch @@ -1330,9 +1270,9 @@ namespace System.Threading.Tasks where TInstance : class { // Validate arguments, but only with asserts, as this is an internal only implementation. - Contract.Assert(thisRef != null, "Expected a non-null thisRef"); - Contract.Assert(beginMethod != null, "Expected a non-null beginMethod"); - Contract.Assert(endMethod != null, "Expected a non-null endMethod"); + Debug.Assert(thisRef != null, "Expected a non-null thisRef"); + Debug.Assert(beginMethod != null, "Expected a non-null beginMethod"); + Debug.Assert(endMethod != null, "Expected a non-null endMethod"); // Create the promise and start the operation. // No try/catch is necessary here as we want exceptions to bubble out, and because @@ -1345,7 +1285,7 @@ namespace System.Threading.Tasks // If it completed synchronously, we'll handle that here. if (asyncResult.CompletedSynchronously) { - Contract.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed."); + Debug.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed."); promise.Complete(thisRef, endMethod, asyncResult, requiresSynchronization: false); } @@ -1425,7 +1365,7 @@ namespace System.Threading.Tasks TInstance thisRef, Func<TInstance, IAsyncResult, TResult> endMethod, IAsyncResult asyncResult, bool requiresSynchronization) { - Contract.Assert(!IsCompleted, "The task should not have been completed yet."); + Debug.Assert(!IsCompleted, "The task should not have been completed yet."); // Run the end method and complete the task bool successfullySet = false; @@ -1454,7 +1394,7 @@ namespace System.Threading.Tasks { successfullySet = TrySetException(exc); } - Contract.Assert(successfullySet, "Expected the task to not yet be completed"); + Debug.Assert(successfullySet, "Expected the task to not yet be completed"); } } @@ -1801,7 +1741,7 @@ namespace System.Threading.Tasks } else { - Contract.Assert(continuationAction != null); + Debug.Assert(continuationAction != null); return starter.ContinueWith<TResult>( // use a cached delegate @@ -1854,7 +1794,7 @@ namespace System.Threading.Tasks } else { - Contract.Assert(continuationAction != null); + Debug.Assert(continuationAction != null); return starter.ContinueWith<TResult>( //the following delegate avoids closure capture as much as possible //completedTasks.Result == tasksCopy; @@ -2200,7 +2140,7 @@ namespace System.Threading.Tasks } else { - Contract.Assert(continuationAction != null); + Debug.Assert(continuationAction != null); return starter.ContinueWith<TResult>( //the following delegate avoids closure capture as much as possible //completedTask.Result is the winning task; state == continuationAction @@ -2246,7 +2186,7 @@ namespace System.Threading.Tasks } else { - Contract.Assert(continuationAction != null); + Debug.Assert(continuationAction != null); return starter.ContinueWith<TResult>( // Use a cached delegate GenericDelegateCache<TAntecedentResult,TResult>.CWAnyActionDelegate, diff --git a/src/mscorlib/src/System/Threading/Tasks/Parallel.cs b/src/mscorlib/src/System/Threading/Tasks/Parallel.cs index 5ec2ae33c0..7808943870 100644 --- a/src/mscorlib/src/System/Threading/Tasks/Parallel.cs +++ b/src/mscorlib/src/System/Threading/Tasks/Parallel.cs @@ -98,7 +98,7 @@ namespace System.Threading.Tasks set { if ((value == 0) || (value < -1)) - throw new ArgumentOutOfRangeException("MaxDegreeOfParallelism"); + throw new ArgumentOutOfRangeException(nameof(MaxDegreeOfParallelism)); m_maxDegreeOfParallelism = value; } } @@ -142,7 +142,6 @@ namespace System.Threading.Tasks /// The <see cref="T:System.Threading.Tasks.Parallel"/> class provides library-based data parallel replacements /// for common operations such as for loops, for each loops, and execution of a set of statements. /// </remarks> - [HostProtection(Synchronization = true, ExternalThreading = true)] public static class Parallel { // static counter for generating unique Fork/Join Context IDs to be used in ETW events @@ -208,11 +207,11 @@ namespace System.Threading.Tasks { if (actions == null) { - throw new ArgumentNullException("actions"); + throw new ArgumentNullException(nameof(actions)); } if (parallelOptions == null) { - throw new ArgumentNullException("parallelOptions"); + throw new ArgumentNullException(nameof(parallelOptions)); } // Throw an ODE if we're passed a disposed CancellationToken. @@ -423,7 +422,7 @@ namespace System.Threading.Tasks { if (body == null) { - throw new ArgumentNullException("body"); + throw new ArgumentNullException(nameof(body)); } return ForWorker<object>( @@ -452,7 +451,7 @@ namespace System.Threading.Tasks { if (body == null) { - throw new ArgumentNullException("body"); + throw new ArgumentNullException(nameof(body)); } return ForWorker64<object>( @@ -491,11 +490,11 @@ namespace System.Threading.Tasks { if (body == null) { - throw new ArgumentNullException("body"); + throw new ArgumentNullException(nameof(body)); } if (parallelOptions == null) { - throw new ArgumentNullException("parallelOptions"); + throw new ArgumentNullException(nameof(parallelOptions)); } return ForWorker<object>( @@ -534,11 +533,11 @@ namespace System.Threading.Tasks { if (body == null) { - throw new ArgumentNullException("body"); + throw new ArgumentNullException(nameof(body)); } if (parallelOptions == null) { - throw new ArgumentNullException("parallelOptions"); + throw new ArgumentNullException(nameof(parallelOptions)); } return ForWorker64<object>( @@ -590,7 +589,7 @@ namespace System.Threading.Tasks { if (body == null) { - throw new ArgumentNullException("body"); + throw new ArgumentNullException(nameof(body)); } return ForWorker<object>( @@ -620,7 +619,7 @@ namespace System.Threading.Tasks { if (body == null) { - throw new ArgumentNullException("body"); + throw new ArgumentNullException(nameof(body)); } return ForWorker64<object>( @@ -661,11 +660,11 @@ namespace System.Threading.Tasks { if (body == null) { - throw new ArgumentNullException("body"); + throw new ArgumentNullException(nameof(body)); } if (parallelOptions == null) { - throw new ArgumentNullException("parallelOptions"); + throw new ArgumentNullException(nameof(parallelOptions)); } return ForWorker<object>( @@ -707,11 +706,11 @@ namespace System.Threading.Tasks { if (body == null) { - throw new ArgumentNullException("body"); + throw new ArgumentNullException(nameof(body)); } if (parallelOptions == null) { - throw new ArgumentNullException("parallelOptions"); + throw new ArgumentNullException(nameof(parallelOptions)); } return ForWorker64<object>( @@ -765,15 +764,15 @@ namespace System.Threading.Tasks { if (body == null) { - throw new ArgumentNullException("body"); + throw new ArgumentNullException(nameof(body)); } if (localInit == null) { - throw new ArgumentNullException("localInit"); + throw new ArgumentNullException(nameof(localInit)); } if (localFinally == null) { - throw new ArgumentNullException("localFinally"); + throw new ArgumentNullException(nameof(localFinally)); } return ForWorker( @@ -827,15 +826,15 @@ namespace System.Threading.Tasks { if (body == null) { - throw new ArgumentNullException("body"); + throw new ArgumentNullException(nameof(body)); } if (localInit == null) { - throw new ArgumentNullException("localInit"); + throw new ArgumentNullException(nameof(localInit)); } if (localFinally == null) { - throw new ArgumentNullException("localFinally"); + throw new ArgumentNullException(nameof(localFinally)); } return ForWorker64( @@ -900,19 +899,19 @@ namespace System.Threading.Tasks { if (body == null) { - throw new ArgumentNullException("body"); + throw new ArgumentNullException(nameof(body)); } if (localInit == null) { - throw new ArgumentNullException("localInit"); + throw new ArgumentNullException(nameof(localInit)); } if (localFinally == null) { - throw new ArgumentNullException("localFinally"); + throw new ArgumentNullException(nameof(localFinally)); } if (parallelOptions == null) { - throw new ArgumentNullException("parallelOptions"); + throw new ArgumentNullException(nameof(parallelOptions)); } return ForWorker( @@ -977,19 +976,19 @@ namespace System.Threading.Tasks { if (body == null) { - throw new ArgumentNullException("body"); + throw new ArgumentNullException(nameof(body)); } if (localInit == null) { - throw new ArgumentNullException("localInit"); + throw new ArgumentNullException(nameof(localInit)); } if (localFinally == null) { - throw new ArgumentNullException("localFinally"); + throw new ArgumentNullException(nameof(localFinally)); } if (parallelOptions == null) { - throw new ArgumentNullException("parallelOptions"); + throw new ArgumentNullException(nameof(parallelOptions)); } @@ -1031,9 +1030,9 @@ namespace System.Threading.Tasks Func<int, ParallelLoopState, TLocal, TLocal> bodyWithLocal, Func<TLocal> localInit, Action<TLocal> localFinally) { - Contract.Assert(((body == null ? 0 : 1) + (bodyWithState == null ? 0 : 1) + (bodyWithLocal == null ? 0 : 1)) == 1, + Debug.Assert(((body == null ? 0 : 1) + (bodyWithState == null ? 0 : 1) + (bodyWithLocal == null ? 0 : 1)) == 1, "expected exactly one body function to be supplied"); - Contract.Assert(bodyWithLocal != null || (localInit == null && localFinally == null), + Debug.Assert(bodyWithLocal != null || (localInit == null && localFinally == null), "thread local functions should only be supplied for loops w/ thread local bodies"); // Instantiate our result. Specifics will be filled in later. @@ -1157,12 +1156,12 @@ namespace System.Threading.Tasks if (bodyWithState != null) { - Contract.Assert(sharedPStateFlags != null); + Debug.Assert(sharedPStateFlags != null); state = new ParallelLoopState32(sharedPStateFlags); } else if (bodyWithLocal != null) { - Contract.Assert(sharedPStateFlags != null); + Debug.Assert(sharedPStateFlags != null); state = new ParallelLoopState32(sharedPStateFlags); if (localInit != null) { @@ -1346,9 +1345,9 @@ namespace System.Threading.Tasks Func<long, ParallelLoopState, TLocal, TLocal> bodyWithLocal, Func<TLocal> localInit, Action<TLocal> localFinally) { - Contract.Assert(((body == null ? 0 : 1) + (bodyWithState == null ? 0 : 1) + (bodyWithLocal == null ? 0 : 1)) == 1, + Debug.Assert(((body == null ? 0 : 1) + (bodyWithState == null ? 0 : 1) + (bodyWithLocal == null ? 0 : 1)) == 1, "expected exactly one body function to be supplied"); - Contract.Assert(bodyWithLocal != null || (localInit == null && localFinally == null), + Debug.Assert(bodyWithLocal != null || (localInit == null && localFinally == null), "thread local functions should only be supplied for loops w/ thread local bodies"); // Instantiate our result. Specifics will be filled in later. @@ -1471,12 +1470,12 @@ namespace System.Threading.Tasks if (bodyWithState != null) { - Contract.Assert(sharedPStateFlags != null); + Debug.Assert(sharedPStateFlags != null); state = new ParallelLoopState64(sharedPStateFlags); } else if (bodyWithLocal != null) { - Contract.Assert(sharedPStateFlags != null); + Debug.Assert(sharedPStateFlags != null); state = new ParallelLoopState64(sharedPStateFlags); // If a thread-local selector was supplied, invoke it. Otherwise, use the default. @@ -1656,11 +1655,11 @@ namespace System.Threading.Tasks { if (source == null) { - throw new ArgumentNullException("source"); + throw new ArgumentNullException(nameof(source)); } if (body == null) { - throw new ArgumentNullException("body"); + throw new ArgumentNullException(nameof(body)); } return ForEachWorker<TSource, object>( @@ -1701,15 +1700,15 @@ namespace System.Threading.Tasks { if (source == null) { - throw new ArgumentNullException("source"); + throw new ArgumentNullException(nameof(source)); } if (body == null) { - throw new ArgumentNullException("body"); + throw new ArgumentNullException(nameof(body)); } if (parallelOptions == null) { - throw new ArgumentNullException("parallelOptions"); + throw new ArgumentNullException(nameof(parallelOptions)); } return ForEachWorker<TSource, object>( @@ -1741,11 +1740,11 @@ namespace System.Threading.Tasks { if (source == null) { - throw new ArgumentNullException("source"); + throw new ArgumentNullException(nameof(source)); } if (body == null) { - throw new ArgumentNullException("body"); + throw new ArgumentNullException(nameof(body)); } return ForEachWorker<TSource, object>( @@ -1788,15 +1787,15 @@ namespace System.Threading.Tasks { if (source == null) { - throw new ArgumentNullException("source"); + throw new ArgumentNullException(nameof(source)); } if (body == null) { - throw new ArgumentNullException("body"); + throw new ArgumentNullException(nameof(body)); } if (parallelOptions == null) { - throw new ArgumentNullException("parallelOptions"); + throw new ArgumentNullException(nameof(parallelOptions)); } return ForEachWorker<TSource, object>( @@ -1828,11 +1827,11 @@ namespace System.Threading.Tasks { if (source == null) { - throw new ArgumentNullException("source"); + throw new ArgumentNullException(nameof(source)); } if (body == null) { - throw new ArgumentNullException("body"); + throw new ArgumentNullException(nameof(body)); } return ForEachWorker<TSource, object>( @@ -1875,15 +1874,15 @@ namespace System.Threading.Tasks { if (source == null) { - throw new ArgumentNullException("source"); + throw new ArgumentNullException(nameof(source)); } if (body == null) { - throw new ArgumentNullException("body"); + throw new ArgumentNullException(nameof(body)); } if (parallelOptions == null) { - throw new ArgumentNullException("parallelOptions"); + throw new ArgumentNullException(nameof(parallelOptions)); } return ForEachWorker<TSource, object>( @@ -1936,19 +1935,19 @@ namespace System.Threading.Tasks { if (source == null) { - throw new ArgumentNullException("source"); + throw new ArgumentNullException(nameof(source)); } if (body == null) { - throw new ArgumentNullException("body"); + throw new ArgumentNullException(nameof(body)); } if (localInit == null) { - throw new ArgumentNullException("localInit"); + throw new ArgumentNullException(nameof(localInit)); } if (localFinally == null) { - throw new ArgumentNullException("localFinally"); + throw new ArgumentNullException(nameof(localFinally)); } return ForEachWorker<TSource, TLocal>( @@ -2013,23 +2012,23 @@ namespace System.Threading.Tasks { if (source == null) { - throw new ArgumentNullException("source"); + throw new ArgumentNullException(nameof(source)); } if (body == null) { - throw new ArgumentNullException("body"); + throw new ArgumentNullException(nameof(body)); } if (localInit == null) { - throw new ArgumentNullException("localInit"); + throw new ArgumentNullException(nameof(localInit)); } if (localFinally == null) { - throw new ArgumentNullException("localFinally"); + throw new ArgumentNullException(nameof(localFinally)); } if (parallelOptions == null) { - throw new ArgumentNullException("parallelOptions"); + throw new ArgumentNullException(nameof(parallelOptions)); } return ForEachWorker<TSource, TLocal>( @@ -2082,19 +2081,19 @@ namespace System.Threading.Tasks { if (source == null) { - throw new ArgumentNullException("source"); + throw new ArgumentNullException(nameof(source)); } if (body == null) { - throw new ArgumentNullException("body"); + throw new ArgumentNullException(nameof(body)); } if (localInit == null) { - throw new ArgumentNullException("localInit"); + throw new ArgumentNullException(nameof(localInit)); } if (localFinally == null) { - throw new ArgumentNullException("localFinally"); + throw new ArgumentNullException(nameof(localFinally)); } return ForEachWorker<TSource, TLocal>( @@ -2158,23 +2157,23 @@ namespace System.Threading.Tasks { if (source == null) { - throw new ArgumentNullException("source"); + throw new ArgumentNullException(nameof(source)); } if (body == null) { - throw new ArgumentNullException("body"); + throw new ArgumentNullException(nameof(body)); } if (localInit == null) { - throw new ArgumentNullException("localInit"); + throw new ArgumentNullException(nameof(localInit)); } if (localFinally == null) { - throw new ArgumentNullException("localFinally"); + throw new ArgumentNullException(nameof(localFinally)); } if (parallelOptions == null) { - throw new ArgumentNullException("parallelOptions"); + throw new ArgumentNullException(nameof(parallelOptions)); } return ForEachWorker<TSource, TLocal>( @@ -2214,10 +2213,10 @@ namespace System.Threading.Tasks Func<TSource, ParallelLoopState, long, TLocal, TLocal> bodyWithEverything, Func<TLocal> localInit, Action<TLocal> localFinally) { - Contract.Assert(((body == null ? 0 : 1) + (bodyWithState == null ? 0 : 1) + + Debug.Assert(((body == null ? 0 : 1) + (bodyWithState == null ? 0 : 1) + (bodyWithStateAndIndex == null ? 0 : 1) + (bodyWithStateAndLocal == null ? 0 : 1) + (bodyWithEverything == null ? 0 : 1)) == 1, "expected exactly one body function to be supplied"); - Contract.Assert((bodyWithStateAndLocal != null) || (bodyWithEverything != null) || (localInit == null && localFinally == null), + Debug.Assert((bodyWithStateAndLocal != null) || (bodyWithEverything != null) || (localInit == null && localFinally == null), "thread local functions should only be supplied for loops w/ thread local bodies"); // Before getting started, do a quick peek to see if we have been canceled already @@ -2278,8 +2277,8 @@ namespace System.Threading.Tasks Func<TSource, ParallelLoopState, long, TLocal, TLocal> bodyWithEverything, Func<TLocal> localInit, Action<TLocal> localFinally) { - Contract.Assert(array != null); - Contract.Assert(parallelOptions != null, "ForEachWorker(array): parallelOptions is null"); + Debug.Assert(array != null); + Debug.Assert(parallelOptions != null, "ForEachWorker(array): parallelOptions is null"); int from = array.GetLowerBound(0); int to = array.GetUpperBound(0) + 1; @@ -2337,8 +2336,8 @@ namespace System.Threading.Tasks Func<TSource, ParallelLoopState, long, TLocal, TLocal> bodyWithEverything, Func<TLocal> localInit, Action<TLocal> localFinally) { - Contract.Assert(list != null); - Contract.Assert(parallelOptions != null, "ForEachWorker(list): parallelOptions is null"); + Debug.Assert(list != null); + Debug.Assert(parallelOptions != null, "ForEachWorker(list): parallelOptions is null"); if (body != null) { @@ -2416,11 +2415,11 @@ namespace System.Threading.Tasks { if (source == null) { - throw new ArgumentNullException("source"); + throw new ArgumentNullException(nameof(source)); } if (body == null) { - throw new ArgumentNullException("body"); + throw new ArgumentNullException(nameof(body)); } return PartitionerForEachWorker<TSource, object>(source, s_defaultParallelOptions, body, null, null, null, null, null, null); @@ -2475,11 +2474,11 @@ namespace System.Threading.Tasks { if (source == null) { - throw new ArgumentNullException("source"); + throw new ArgumentNullException(nameof(source)); } if (body == null) { - throw new ArgumentNullException("body"); + throw new ArgumentNullException(nameof(body)); } return PartitionerForEachWorker<TSource, object>(source, s_defaultParallelOptions, null, body, null, null, null, null, null); @@ -2537,11 +2536,11 @@ namespace System.Threading.Tasks { if (source == null) { - throw new ArgumentNullException("source"); + throw new ArgumentNullException(nameof(source)); } if (body == null) { - throw new ArgumentNullException("body"); + throw new ArgumentNullException(nameof(body)); } if (!source.KeysNormalized) @@ -2621,19 +2620,19 @@ namespace System.Threading.Tasks { if (source == null) { - throw new ArgumentNullException("source"); + throw new ArgumentNullException(nameof(source)); } if (body == null) { - throw new ArgumentNullException("body"); + throw new ArgumentNullException(nameof(body)); } if (localInit == null) { - throw new ArgumentNullException("localInit"); + throw new ArgumentNullException(nameof(localInit)); } if (localFinally == null) { - throw new ArgumentNullException("localFinally"); + throw new ArgumentNullException(nameof(localFinally)); } return PartitionerForEachWorker<TSource, TLocal>(source, s_defaultParallelOptions, null, null, null, body, null, localInit, localFinally); @@ -2711,19 +2710,19 @@ namespace System.Threading.Tasks { if (source == null) { - throw new ArgumentNullException("source"); + throw new ArgumentNullException(nameof(source)); } if (body == null) { - throw new ArgumentNullException("body"); + throw new ArgumentNullException(nameof(body)); } if (localInit == null) { - throw new ArgumentNullException("localInit"); + throw new ArgumentNullException(nameof(localInit)); } if (localFinally == null) { - throw new ArgumentNullException("localFinally"); + throw new ArgumentNullException(nameof(localFinally)); } if (!source.KeysNormalized) @@ -2793,15 +2792,15 @@ namespace System.Threading.Tasks { if (source == null) { - throw new ArgumentNullException("source"); + throw new ArgumentNullException(nameof(source)); } if (body == null) { - throw new ArgumentNullException("body"); + throw new ArgumentNullException(nameof(body)); } if (parallelOptions == null) { - throw new ArgumentNullException("parallelOptions"); + throw new ArgumentNullException(nameof(parallelOptions)); } return PartitionerForEachWorker<TSource, object>(source, parallelOptions, body, null, null, null, null, null, null); @@ -2868,15 +2867,15 @@ namespace System.Threading.Tasks { if (source == null) { - throw new ArgumentNullException("source"); + throw new ArgumentNullException(nameof(source)); } if (body == null) { - throw new ArgumentNullException("body"); + throw new ArgumentNullException(nameof(body)); } if (parallelOptions == null) { - throw new ArgumentNullException("parallelOptions"); + throw new ArgumentNullException(nameof(parallelOptions)); } return PartitionerForEachWorker<TSource, object>(source, parallelOptions, null, body, null, null, null, null, null); @@ -2946,15 +2945,15 @@ namespace System.Threading.Tasks { if (source == null) { - throw new ArgumentNullException("source"); + throw new ArgumentNullException(nameof(source)); } if (body == null) { - throw new ArgumentNullException("body"); + throw new ArgumentNullException(nameof(body)); } if (parallelOptions == null) { - throw new ArgumentNullException("parallelOptions"); + throw new ArgumentNullException(nameof(parallelOptions)); } if (!source.KeysNormalized) @@ -3046,23 +3045,23 @@ namespace System.Threading.Tasks { if (source == null) { - throw new ArgumentNullException("source"); + throw new ArgumentNullException(nameof(source)); } if (body == null) { - throw new ArgumentNullException("body"); + throw new ArgumentNullException(nameof(body)); } if (localInit == null) { - throw new ArgumentNullException("localInit"); + throw new ArgumentNullException(nameof(localInit)); } if (localFinally == null) { - throw new ArgumentNullException("localFinally"); + throw new ArgumentNullException(nameof(localFinally)); } if (parallelOptions == null) { - throw new ArgumentNullException("parallelOptions"); + throw new ArgumentNullException(nameof(parallelOptions)); } return PartitionerForEachWorker<TSource, TLocal>(source, parallelOptions, null, null, null, body, null, localInit, localFinally); @@ -3152,23 +3151,23 @@ namespace System.Threading.Tasks { if (source == null) { - throw new ArgumentNullException("source"); + throw new ArgumentNullException(nameof(source)); } if (body == null) { - throw new ArgumentNullException("body"); + throw new ArgumentNullException(nameof(body)); } if (localInit == null) { - throw new ArgumentNullException("localInit"); + throw new ArgumentNullException(nameof(localInit)); } if (localFinally == null) { - throw new ArgumentNullException("localFinally"); + throw new ArgumentNullException(nameof(localFinally)); } if (parallelOptions == null) { - throw new ArgumentNullException("parallelOptions"); + throw new ArgumentNullException(nameof(parallelOptions)); } if (!source.KeysNormalized) @@ -3191,14 +3190,14 @@ namespace System.Threading.Tasks Func<TLocal> localInit, Action<TLocal> localFinally) { - Contract.Assert(((simpleBody == null ? 0 : 1) + (bodyWithState == null ? 0 : 1) + + Debug.Assert(((simpleBody == null ? 0 : 1) + (bodyWithState == null ? 0 : 1) + (bodyWithStateAndIndex == null ? 0 : 1) + (bodyWithStateAndLocal == null ? 0 : 1) + (bodyWithEverything == null ? 0 : 1)) == 1, "PartitionForEach: expected exactly one body function to be supplied"); - Contract.Assert((bodyWithStateAndLocal != null) || (bodyWithEverything != null) || (localInit == null && localFinally == null), + Debug.Assert((bodyWithStateAndLocal != null) || (bodyWithEverything != null) || (localInit == null && localFinally == null), "PartitionForEach: thread local functions should only be supplied for loops w/ thread local bodies"); OrderablePartitioner<TSource> orderedSource = source as OrderablePartitioner<TSource>; - Contract.Assert((orderedSource != null) || (bodyWithStateAndIndex == null && bodyWithEverything == null), + Debug.Assert((orderedSource != null) || (bodyWithStateAndIndex == null && bodyWithEverything == null), "PartitionForEach: bodies with indices are only allowable for OrderablePartitioner"); if (!source.SupportsDynamicPartitions) @@ -3401,7 +3400,7 @@ namespace System.Threading.Tasks else if (bodyWithStateAndLocal != null) localValue = bodyWithStateAndLocal(t, state, localValue); else - Contract.Assert(false, "PartitionerForEach: illegal body type in Partitioner handler"); + Debug.Assert(false, "PartitionerForEach: illegal body type in Partitioner handler"); // Any break, stop or exception causes us to halt @@ -3576,7 +3575,7 @@ namespace System.Threading.Tasks public bool LimitExceeded() { - Contract.Assert(m_timeLimit != 0, "Probably the default initializer for LoopTimer was used somewhere"); + Debug.Assert(m_timeLimit != 0, "Probably the default initializer for LoopTimer was used somewhere"); // comparing against the next expected time saves an addition operation here // Also we omit the comparison for wrap around here. The only side effect is one extra early yield every 38 days. diff --git a/src/mscorlib/src/System/Threading/Tasks/ParallelLoopState.cs b/src/mscorlib/src/System/Threading/Tasks/ParallelLoopState.cs index 4db3a9d105..6a62cf8977 100644 --- a/src/mscorlib/src/System/Threading/Tasks/ParallelLoopState.cs +++ b/src/mscorlib/src/System/Threading/Tasks/ParallelLoopState.cs @@ -26,7 +26,6 @@ namespace System.Threading.Tasks /// Enables iterations of <see cref="T:System.Threading.Tasks.Parallel"/> loops to interact with /// other iterations. /// </summary> - [HostProtection(Synchronization = true, ExternalThreading = true)] [DebuggerDisplay("ShouldExitCurrentIteration = {ShouldExitCurrentIteration}")] public class ParallelLoopState { @@ -47,7 +46,7 @@ namespace System.Threading.Tasks { get { - Contract.Assert(false); + Debug.Assert(false); throw new NotSupportedException( Environment.GetResourceString("ParallelState_NotSupportedException_UnsupportedMethod")); } @@ -104,7 +103,7 @@ namespace System.Threading.Tasks { get { - Contract.Assert(false); + Debug.Assert(false); throw new NotSupportedException( Environment.GetResourceString("ParallelState_NotSupportedException_UnsupportedMethod")); } @@ -152,7 +151,7 @@ namespace System.Threading.Tasks // Internal/virtual support for Break(). internal virtual void InternalBreak() { - Contract.Assert(false); + Debug.Assert(false); throw new NotSupportedException( Environment.GetResourceString("ParallelState_NotSupportedException_UnsupportedMethod")); } diff --git a/src/mscorlib/src/System/Threading/Tasks/ParallelRangeManager.cs b/src/mscorlib/src/System/Threading/Tasks/ParallelRangeManager.cs index c4b66c41a9..49f61a6614 100644 --- a/src/mscorlib/src/System/Threading/Tasks/ParallelRangeManager.cs +++ b/src/mscorlib/src/System/Threading/Tasks/ParallelRangeManager.cs @@ -12,6 +12,7 @@ using System; using System.Threading; +using System.Diagnostics; using System.Diagnostics.Contracts; #pragma warning disable 0420 @@ -160,7 +161,7 @@ namespace System.Threading.Tasks bool bRetVal = FindNewWork(out nFromInclusiveLocal, out nToExclusiveLocal); - Contract.Assert((nFromInclusiveLocal <= Int32.MaxValue) && (nFromInclusiveLocal >= Int32.MinValue) && + Debug.Assert((nFromInclusiveLocal <= Int32.MaxValue) && (nFromInclusiveLocal >= Int32.MinValue) && (nToExclusiveLocal <= Int32.MaxValue) && (nToExclusiveLocal >= Int32.MinValue)); // convert to 32 bit before returning @@ -218,7 +219,7 @@ namespace System.Threading.Tasks // // find the actual number of index ranges we will need // - Contract.Assert((uSpan / uRangeSize) < Int32.MaxValue); + Debug.Assert((uSpan / uRangeSize) < Int32.MaxValue); int nNumRanges = (int)(uSpan / uRangeSize); @@ -251,7 +252,7 @@ namespace System.Threading.Tasks nCurrentIndex > nToExclusive) { // this should only happen at the last index - Contract.Assert(i == nNumRanges - 1); + Debug.Assert(i == nNumRanges - 1); nCurrentIndex = nToExclusive; } @@ -267,7 +268,7 @@ namespace System.Threading.Tasks /// </summary> internal RangeWorker RegisterNewWorker() { - Contract.Assert(m_indexRanges != null && m_indexRanges.Length != 0); + Debug.Assert(m_indexRanges != null && m_indexRanges.Length != 0); int nInitialRange = (Interlocked.Increment(ref m_nCurrentIndexRangeToAssign) - 1) % m_indexRanges.Length; diff --git a/src/mscorlib/src/System/Threading/Tasks/ProducerConsumerQueues.cs b/src/mscorlib/src/System/Threading/Tasks/ProducerConsumerQueues.cs index 462ee0a9bd..6b9dfbbe37 100644 --- a/src/mscorlib/src/System/Threading/Tasks/ProducerConsumerQueues.cs +++ b/src/mscorlib/src/System/Threading/Tasks/ProducerConsumerQueues.cs @@ -140,10 +140,10 @@ namespace System.Threading.Tasks internal SingleProducerSingleConsumerQueue() { // Validate constants in ctor rather than in an explicit cctor that would cause perf degradation - Contract.Assert(INIT_SEGMENT_SIZE > 0, "Initial segment size must be > 0."); - Contract.Assert((INIT_SEGMENT_SIZE & (INIT_SEGMENT_SIZE - 1)) == 0, "Initial segment size must be a power of 2"); - Contract.Assert(INIT_SEGMENT_SIZE <= MAX_SEGMENT_SIZE, "Initial segment size should be <= maximum."); - Contract.Assert(MAX_SEGMENT_SIZE < Int32.MaxValue / 2, "Max segment size * 2 must be < Int32.MaxValue, or else overflow could occur."); + Debug.Assert(INIT_SEGMENT_SIZE > 0, "Initial segment size must be > 0."); + Debug.Assert((INIT_SEGMENT_SIZE & (INIT_SEGMENT_SIZE - 1)) == 0, "Initial segment size must be a power of 2"); + Debug.Assert(INIT_SEGMENT_SIZE <= MAX_SEGMENT_SIZE, "Initial segment size should be <= maximum."); + Debug.Assert(MAX_SEGMENT_SIZE < Int32.MaxValue / 2, "Max segment size * 2 must be < Int32.MaxValue, or else overflow could occur."); // Initialize the queue m_head = m_tail = new Segment(INIT_SEGMENT_SIZE); @@ -183,7 +183,7 @@ namespace System.Threading.Tasks } int newSegmentSize = m_tail.m_array.Length << 1; // double size - Contract.Assert(newSegmentSize > 0, "The max size should always be small enough that we don't overflow."); + Debug.Assert(newSegmentSize > 0, "The max size should always be small enough that we don't overflow."); if (newSegmentSize > MAX_SEGMENT_SIZE) newSegmentSize = MAX_SEGMENT_SIZE; var newSegment = new Segment(newSegmentSize); @@ -456,7 +456,7 @@ namespace System.Threading.Tasks /// <remarks>The Count is not thread safe, so we need to acquire the lock.</remarks> int IProducerConsumerQueue<T>.GetCountSafe(object syncObj) { - Contract.Assert(syncObj != null, "The syncObj parameter is null."); + Debug.Assert(syncObj != null, "The syncObj parameter is null."); lock (syncObj) { return Count; diff --git a/src/mscorlib/src/System/Threading/Tasks/TPLETWProvider.cs b/src/mscorlib/src/System/Threading/Tasks/TPLETWProvider.cs index 5f79f30b35..325aa91b44 100644 --- a/src/mscorlib/src/System/Threading/Tasks/TPLETWProvider.cs +++ b/src/mscorlib/src/System/Threading/Tasks/TPLETWProvider.cs @@ -216,7 +216,6 @@ namespace System.Threading.Tasks /// <param name="OperationType">The kind of fork/join operation.</param> /// <param name="InclusiveFrom">The lower bound of the loop.</param> /// <param name="ExclusiveTo">The upper bound of the loop.</param> - [SecuritySafeCritical] [Event(PARALLELLOOPBEGIN_ID, Level = EventLevel.Informational, ActivityOptions=EventActivityOptions.Recursive, Task = TplEtwProvider.Tasks.Loop, Opcode = EventOpcode.Start)] public void ParallelLoopBegin( @@ -261,7 +260,6 @@ namespace System.Threading.Tasks /// <param name="OriginatingTaskID">The task ID.</param> /// <param name="ForkJoinContextID">The loop ID.</param> /// <param name="TotalIterations">the total number of iterations processed.</param> - [SecuritySafeCritical] [Event(PARALLELLOOPEND_ID, Level = EventLevel.Informational, Task = TplEtwProvider.Tasks.Loop, Opcode = EventOpcode.Stop)] public void ParallelLoopEnd( int OriginatingTaskSchedulerID, int OriginatingTaskID, // PFX_COMMON_EVENT_HEADER @@ -298,7 +296,6 @@ namespace System.Threading.Tasks /// <param name="ForkJoinContextID">The invoke ID.</param> /// <param name="OperationType">The kind of fork/join operation.</param> /// <param name="ActionCount">The number of actions being invoked.</param> - [SecuritySafeCritical] [Event(PARALLELINVOKEBEGIN_ID, Level = EventLevel.Informational, ActivityOptions=EventActivityOptions.Recursive, Task = TplEtwProvider.Tasks.Invoke, Opcode = EventOpcode.Start)] public void ParallelInvokeBegin( @@ -412,7 +409,6 @@ namespace System.Threading.Tasks /// <param name="TaskID">The task ID.</param> /// <param name="CreatingTaskID">The task ID</param> /// <param name="TaskCreationOptions">The options used to create the task.</param> - [SecuritySafeCritical] [Event(TASKSCHEDULED_ID, Task = Tasks.TaskScheduled, Version=1, Opcode = EventOpcode.Send, Level = EventLevel.Informational, Keywords = Keywords.TaskTransfer|Keywords.Tasks)] public void TaskScheduled( @@ -475,7 +471,6 @@ namespace System.Threading.Tasks /// <param name="OriginatingTaskID">The task ID.</param> /// <param name="TaskID">The task ID.</param> /// <param name="IsExceptional">Whether the task completed due to an error.</param> - [SecuritySafeCritical] [Event(TASKCOMPLETED_ID, Version=1, Level = EventLevel.Informational, Keywords = Keywords.TaskStops)] public void TaskCompleted( @@ -513,7 +508,6 @@ namespace System.Threading.Tasks /// <param name="ContinueWithTaskID">If known, if 'TaskID' has a 'continueWith' task, mention give its ID here. /// 0 means unknown. This allows better visualization of the common sequential chaining case.</param> /// </summary> - [SecuritySafeCritical] [Event(TASKWAITBEGIN_ID, Version=3, Task = TplEtwProvider.Tasks.TaskWait, Opcode = EventOpcode.Send, Level = EventLevel.Informational, Keywords = Keywords.TaskTransfer|Keywords.Tasks)] public void TaskWaitBegin( @@ -600,7 +594,6 @@ namespace System.Threading.Tasks /// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param> /// <param name="OriginatingTaskID">The task ID.</param> /// <param name="TaskID">The activityId for the continuation.</param> - [SecuritySafeCritical] [Event(AWAITTASKCONTINUATIONSCHEDULED_ID, Task = Tasks.AwaitTaskContinuationScheduled, Opcode = EventOpcode.Send, Level = EventLevel.Informational, Keywords = Keywords.TaskTransfer|Keywords.Tasks)] public void AwaitTaskContinuationScheduled( @@ -629,7 +622,6 @@ namespace System.Threading.Tasks } } - [SecuritySafeCritical] [Event(TRACEOPERATIONSTART_ID, Version=1, Level = EventLevel.Informational, Keywords = Keywords.AsyncCausalityOperation)] public void TraceOperationBegin(int TaskID, string OperationName, long RelatedContext) @@ -655,7 +647,6 @@ namespace System.Threading.Tasks } } - [SecuritySafeCritical] [Event(TRACEOPERATIONRELATION_ID, Version=1, Level = EventLevel.Informational, Keywords = Keywords.AsyncCausalityRelation)] public void TraceOperationRelation(int TaskID, CausalityRelation Relation) @@ -664,7 +655,6 @@ namespace System.Threading.Tasks WriteEvent(TRACEOPERATIONRELATION_ID, TaskID,(int) Relation); // optmized overload for this exists } - [SecuritySafeCritical] [Event(TRACEOPERATIONSTOP_ID, Version=1, Level = EventLevel.Informational, Keywords = Keywords.AsyncCausalityOperation)] public void TraceOperationEnd(int TaskID, AsyncCausalityStatus Status) @@ -673,7 +663,6 @@ namespace System.Threading.Tasks WriteEvent(TRACEOPERATIONSTOP_ID, TaskID,(int) Status); // optmized overload for this exists } - [SecuritySafeCritical] [Event(TRACESYNCHRONOUSWORKSTART_ID, Version=1, Level = EventLevel.Informational, Keywords = Keywords.AsyncCausalitySynchronousWork)] public void TraceSynchronousWorkBegin(int TaskID, CausalitySynchronousWork Work) @@ -682,7 +671,6 @@ namespace System.Threading.Tasks WriteEvent(TRACESYNCHRONOUSWORKSTART_ID, TaskID,(int) Work); // optmized overload for this exists } - [SecuritySafeCritical] [Event(TRACESYNCHRONOUSWORKSTOP_ID, Version=1, Level = EventLevel.Informational, Keywords = Keywords.AsyncCausalitySynchronousWork)] public void TraceSynchronousWorkEnd(CausalitySynchronousWork Work) diff --git a/src/mscorlib/src/System/Threading/Tasks/Task.cs b/src/mscorlib/src/System/Threading/Tasks/Task.cs index 36f8401a4d..cf081f75fd 100644 --- a/src/mscorlib/src/System/Threading/Tasks/Task.cs +++ b/src/mscorlib/src/System/Threading/Tasks/Task.cs @@ -137,7 +137,6 @@ namespace System.Threading.Tasks /// InternalWait method serves a potential marker for when a Task is entering a wait operation. /// </para> /// </remarks> - [HostProtection(Synchronization = true, ExternalThreading = true)] [DebuggerTypeProxy(typeof(SystemThreadingTasks_TaskDebugView))] [DebuggerDisplay("Id = {Id}, Status = {Status}, Method = {DebuggerDisplayMethodDescription}")] public class Task : IThreadPoolWorkItem, IAsyncResult, IDisposable @@ -152,7 +151,7 @@ namespace System.Threading.Tasks private volatile int m_taskId; // this task's unique ID. initialized only if it is ever requested - internal object m_action; // The body of the task. Might be Action<object>, Action<TState> or Action. Or possibly a Func. + internal Delegate m_action; // The body of the task. Might be Action<object>, Action<TState> or Action. Or possibly a Func. // If m_action is set to null it will indicate that we operate in the // "externally triggered completion" mode, which is exclusively meant // for the signalling Task<TResult> (aka. promise). In this mode, @@ -339,7 +338,7 @@ namespace System.Threading.Tasks // (action,TCO). It should always be true. internal Task(object state, TaskCreationOptions creationOptions, bool promiseStyle) { - Contract.Assert(promiseStyle, "Promise CTOR: promiseStyle was false"); + Debug.Assert(promiseStyle, "Promise CTOR: promiseStyle was false"); // Check the creationOptions. We allow the AttachedToParent option to be specified for promise tasks. // Also allow RunContinuationsAsynchronously because this is the constructor called by TCS @@ -580,7 +579,7 @@ namespace System.Threading.Tasks /// <param name="cancellationToken">A CancellationToken for the Task.</param> /// <param name="creationOptions">Options to customize behavior of Task.</param> /// <param name="internalOptions">Internal options to customize behavior of Task.</param> - internal void TaskConstructorCore(object action, object state, CancellationToken cancellationToken, + internal void TaskConstructorCore(Delegate action, object state, CancellationToken cancellationToken, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions, TaskScheduler scheduler) { m_action = action; @@ -609,7 +608,7 @@ namespace System.Threading.Tasks InternalTaskOptions.ContinuationTask | InternalTaskOptions.LazyCancellation | InternalTaskOptions.QueuedByRuntime)); - Contract.Assert(illegalInternalOptions == 0, "TaskConstructorCore: Illegal internal options"); + Debug.Assert(illegalInternalOptions == 0, "TaskConstructorCore: Illegal internal options"); #endif // Throw exception if the user specifies both LongRunning and SelfReplicating @@ -620,8 +619,8 @@ namespace System.Threading.Tasks } // Assign options to m_stateAndOptionsFlag. - Contract.Assert(m_stateFlags == 0, "TaskConstructorCore: non-zero m_stateFlags"); - Contract.Assert((((int)creationOptions) | OptionsMask) == OptionsMask, "TaskConstructorCore: options take too many bits"); + Debug.Assert(m_stateFlags == 0, "TaskConstructorCore: non-zero m_stateFlags"); + Debug.Assert((((int)creationOptions) | OptionsMask) == OptionsMask, "TaskConstructorCore: options take too many bits"); var tmpFlags = (int)creationOptions | (int)internalOptions; if ((m_action == null) || ((internalOptions & InternalTaskOptions.ContinuationTask) != 0)) { @@ -649,7 +648,7 @@ namespace System.Threading.Tasks // we need to do this as the very last thing in the construction path, because the CT registration could modify m_stateFlags if (cancellationToken.CanBeCanceled) { - Contract.Assert((internalOptions & + Debug.Assert((internalOptions & (InternalTaskOptions.ChildReplica | InternalTaskOptions.SelfReplicating | InternalTaskOptions.ContinuationTask)) == 0, "TaskConstructorCore: Did not expect to see cancelable token for replica/replicating or continuation task."); @@ -743,7 +742,7 @@ namespace System.Threading.Tasks antecedentTask.RemoveContinuation(continuation); } } - Contract.Assert(targetTask != null, + Debug.Assert(targetTask != null, "targetTask should have been non-null, with the supplied argument being a task or a tuple containing one"); targetTask.InternalCancel(false); } @@ -753,7 +752,7 @@ namespace System.Threading.Tasks { get { - Delegate d = (Delegate)m_action; + Delegate d = m_action; return d != null ? d.Method.ToString() : "{null}"; } } @@ -764,10 +763,9 @@ namespace System.Threading.Tasks /// </summary> /// <param name="stackMark">A stack crawl mark pointing to the frame of the caller.</param> - [SecuritySafeCritical] internal void PossiblyCaptureContext(ref StackCrawlMark stackMark) { - Contract.Assert(m_contingentProperties == null || m_contingentProperties.m_capturedContext == null, + Debug.Assert(m_contingentProperties == null || m_contingentProperties.m_capturedContext == null, "Captured an ExecutionContext when one was already captured."); // In the legacy .NET 3.5 build, we don't have the optimized overload of Capture() @@ -791,7 +789,7 @@ namespace System.Threading.Tasks // a read of the volatile m_stateFlags field. internal static TaskCreationOptions OptionsMethod(int flags) { - Contract.Assert((OptionsMask & 1) == 1, "OptionsMask needs a shift in Options.get"); + Debug.Assert((OptionsMask & 1) == 1, "OptionsMask needs a shift in Options.get"); return (TaskCreationOptions)(flags & OptionsMask); } @@ -841,7 +839,7 @@ namespace System.Threading.Tasks /// <param name="enabled">true to set the bit; false to unset the bit.</param> internal void SetNotificationForWaitCompletion(bool enabled) { - Contract.Assert((Options & (TaskCreationOptions)InternalTaskOptions.PromiseTask) != 0, + Debug.Assert((Options & (TaskCreationOptions)InternalTaskOptions.PromiseTask) != 0, "Should only be used for promise-style tasks"); // hasn't been vetted on other kinds as there hasn't been a need if (enabled) @@ -849,7 +847,7 @@ namespace System.Threading.Tasks // Atomically set the END_AWAIT_NOTIFICATION bit bool success = AtomicStateUpdate(TASK_STATE_WAIT_COMPLETION_NOTIFICATION, TASK_STATE_COMPLETED_MASK | TASK_STATE_COMPLETION_RESERVED); - Contract.Assert(success, "Tried to set enabled on completed Task"); + Debug.Assert(success, "Tried to set enabled on completed Task"); } else { @@ -886,7 +884,7 @@ namespace System.Threading.Tasks /// <returns>true if any of the tasks require notification; otherwise, false.</returns> internal static bool AnyTaskRequiresNotifyDebuggerOfWaitCompletion(Task[] tasks) { - Contract.Assert(tasks != null, "Expected non-null array of tasks"); + Debug.Assert(tasks != null, "Expected non-null array of tasks"); foreach (var task in tasks) { if (task != null && @@ -926,7 +924,7 @@ namespace System.Threading.Tasks // bit was unset between the time that it was checked and this method was called. // It's so remote a chance that it's worth having the assert to protect against misuse. bool isWaitNotificationEnabled = IsWaitNotificationEnabled; - Contract.Assert(isWaitNotificationEnabled, "Should only be called if the wait completion bit is set."); + Debug.Assert(isWaitNotificationEnabled, "Should only be called if the wait completion bit is set."); return isWaitNotificationEnabled; } } @@ -946,7 +944,7 @@ namespace System.Threading.Tasks // It's theoretically possible but extremely rare that this assert could fire because the // bit was unset between the time that it was checked and this method was called. // It's so remote a chance that it's worth having the assert to protect against misuse. - Contract.Assert(IsWaitNotificationEnabled, "Should only be called if the wait completion bit is set."); + Debug.Assert(IsWaitNotificationEnabled, "Should only be called if the wait completion bit is set."); // Now that we're notifying the debugger, clear the bit. The debugger should do this anyway, // but this adds a bit of protection in case it fails to, and given that the debugger is involved, @@ -991,7 +989,7 @@ namespace System.Threading.Tasks /// </summary> internal void AddNewChild() { - Contract.Assert(Task.InternalCurrent == this || this.IsSelfReplicatingRoot, "Task.AddNewChild(): Called from an external context"); + Debug.Assert(Task.InternalCurrent == this || this.IsSelfReplicatingRoot, "Task.AddNewChild(): Called from an external context"); var props = EnsureContingentPropertiesInitialized(); @@ -1014,10 +1012,10 @@ namespace System.Threading.Tasks // We need to subtract that child from m_completionCountdown, or the parent will never complete. internal void DisregardChild() { - Contract.Assert(Task.InternalCurrent == this, "Task.DisregardChild(): Called from an external context"); + Debug.Assert(Task.InternalCurrent == this, "Task.DisregardChild(): Called from an external context"); var props = EnsureContingentPropertiesInitialized(); - Contract.Assert(props.m_completionCountdown >= 2, "Task.DisregardChild(): Expected parent count to be >= 2"); + Debug.Assert(props.m_completionCountdown >= 2, "Task.DisregardChild(): Expected parent count to be >= 2"); Interlocked.Decrement(ref props.m_completionCountdown); } @@ -1161,7 +1159,6 @@ namespace System.Threading.Tasks // // Internal version of RunSynchronously that allows not waiting for completion. // - [SecuritySafeCritical] // Needed for QueueTask internal void InternalRunSynchronously(TaskScheduler scheduler, bool waitForCompletion) { Contract.Requires(scheduler != null, "Task.InternalRunSynchronously(): null TaskScheduler"); @@ -1235,7 +1232,7 @@ namespace System.Threading.Tasks // Mark ourselves as "handled" to avoid crashing the finalizer thread if the caller neglects to // call Wait() on this task. // m_contingentProperties.m_exceptionsHolder *should* already exist after AddException() - Contract.Assert( + Debug.Assert( (m_contingentProperties != null) && (m_contingentProperties.m_exceptionsHolder != null) && (m_contingentProperties.m_exceptionsHolder.ContainsFaultList), @@ -1252,7 +1249,7 @@ namespace System.Threading.Tasks } else { - Contract.Assert((m_stateFlags & TASK_STATE_CANCELED) != 0, "Task.RunSynchronously: expected TASK_STATE_CANCELED to be set"); + Debug.Assert((m_stateFlags & TASK_STATE_CANCELED) != 0, "Task.RunSynchronously: expected TASK_STATE_CANCELED to be set"); // Can't call this method on canceled task. ThrowHelper.ThrowInvalidOperationException(ExceptionResource.Task_RunSynchronously_TaskCompleted); } @@ -1403,7 +1400,7 @@ namespace System.Threading.Tasks // Only return an exception in faulted state (skip manufactured exceptions) // A "benevolent" race condition makes it possible to return null when IsFaulted is // true (i.e., if IsFaulted is set just after the check to IsFaulted above). - Contract.Assert((e == null) || IsFaulted, "Task.Exception_get(): returning non-null value when not Faulted"); + Debug.Assert((e == null) || IsFaulted, "Task.Exception_get(): returning non-null value when not Faulted"); return e; } @@ -1884,11 +1881,10 @@ namespace System.Threading.Tasks /// underneath us. If false, TASK_STATE_STARTED bit is OR-ed right in. This /// allows us to streamline things a bit for StartNew(), where competing cancellations /// are not a problem.</param> - [SecuritySafeCritical] // Needed for QueueTask internal void ScheduleAndStart(bool needsProtection) { - Contract.Assert(m_taskScheduler != null, "expected a task scheduler to have been selected"); - Contract.Assert((m_stateFlags & TASK_STATE_STARTED) == 0, "task has already started"); + Debug.Assert(m_taskScheduler != null, "expected a task scheduler to have been selected"); + Debug.Assert((m_stateFlags & TASK_STATE_STARTED) == 0, "task has already started"); // Set the TASK_STATE_STARTED bit if (needsProtection) @@ -1912,7 +1908,7 @@ namespace System.Threading.Tasks if (AsyncCausalityTracer.LoggingOn && (Options & (TaskCreationOptions)InternalTaskOptions.ContinuationTask) == 0) { //For all other task than TaskContinuations we want to log. TaskContinuations log in their constructor - AsyncCausalityTracer.TraceOperationCreation(CausalityTraceLevel.Required, this.Id, "Task: "+((Delegate)m_action).Method.Name, 0); + AsyncCausalityTracer.TraceOperationCreation(CausalityTraceLevel.Required, this.Id, "Task: " + m_action.Method.Name, 0); } @@ -1942,7 +1938,7 @@ namespace System.Threading.Tasks if ((Options & (TaskCreationOptions)InternalTaskOptions.ContinuationTask) == 0) { // m_contingentProperties.m_exceptionsHolder *should* already exist after AddException() - Contract.Assert( + Debug.Assert( (m_contingentProperties != null) && (m_contingentProperties.m_exceptionsHolder != null) && (m_contingentProperties.m_exceptionsHolder.ContainsFaultList), @@ -1981,13 +1977,13 @@ namespace System.Threading.Tasks var eoAsEdi = exceptionObject as ExceptionDispatchInfo; var eoAsEnumerableEdi = exceptionObject as IEnumerable<ExceptionDispatchInfo>; - Contract.Assert( + Debug.Assert( eoAsException != null || eoAsEnumerableException != null || eoAsEdi != null || eoAsEnumerableEdi != null, "Task.AddException: Expected an Exception, ExceptionDispatchInfo, or an IEnumerable<> of one of those"); var eoAsOce = exceptionObject as OperationCanceledException; - Contract.Assert( + Debug.Assert( !representsCancellation || eoAsOce != null || (eoAsEdi != null && eoAsEdi.SourceException is OperationCanceledException), @@ -2078,7 +2074,7 @@ namespace System.Threading.Tasks { // There are exceptions; get the aggregate and optionally add the canceled // exception to the aggregate (if applicable). - Contract.Assert(m_contingentProperties != null); // ExceptionRecorded ==> m_contingentProperties != null + Debug.Assert(m_contingentProperties != null); // ExceptionRecorded ==> m_contingentProperties != null // No need to lock around this, as other logic prevents the consumption of exceptions // before they have been completely processed. @@ -2097,7 +2093,7 @@ namespace System.Threading.Tasks internal ReadOnlyCollection<ExceptionDispatchInfo> GetExceptionDispatchInfos() { bool exceptionsAvailable = IsFaulted && ExceptionRecorded; - Contract.Assert(exceptionsAvailable, "Must only be used when the task has faulted with exceptions."); + Debug.Assert(exceptionsAvailable, "Must only be used when the task has faulted with exceptions."); return exceptionsAvailable ? m_contingentProperties.m_exceptionsHolder.GetExceptionDispatchInfos() : new ReadOnlyCollection<ExceptionDispatchInfo>(new ExceptionDispatchInfo[0]); @@ -2107,7 +2103,7 @@ namespace System.Threading.Tasks /// <returns>The ExceptionDispatchInfo. May be null if no OCE was stored for the task.</returns> internal ExceptionDispatchInfo GetCancellationExceptionDispatchInfo() { - Contract.Assert(IsCanceled, "Must only be used when the task has canceled."); + Debug.Assert(IsCanceled, "Must only be used when the task has canceled."); return Volatile.Read(ref m_contingentProperties)?.m_exceptionsHolder?.GetCancellationExceptionDispatchInfo(); // may be null } @@ -2344,7 +2340,7 @@ namespace System.Threading.Tasks Contract.Requires(childTask != null); Contract.Requires(childTask.IsCompleted, "ProcessChildCompletion was called for an uncompleted task"); - Contract.Assert(childTask.m_contingentProperties?.m_parent == this, "ProcessChildCompletion should only be called for a child of this task"); + Debug.Assert(childTask.m_contingentProperties?.m_parent == this, "ProcessChildCompletion should only be called for a child of this task"); var props = Volatile.Read(ref m_contingentProperties); @@ -2404,11 +2400,11 @@ namespace System.Threading.Tasks { // Ensure any exceptions thrown by children are added to the parent. // In doing this, we are implicitly marking children as being "handled". - Contract.Assert(task.IsCompleted, "Expected all tasks in list to be completed"); + Debug.Assert(task.IsCompleted, "Expected all tasks in list to be completed"); if (task.IsFaulted && !task.IsExceptionObservedByParent) { TaskExceptionHolder exceptionHolder = Volatile.Read(ref task.m_contingentProperties).m_exceptionsHolder; - Contract.Assert(exceptionHolder != null); + Debug.Assert(exceptionHolder != null); // No locking necessary since child task is finished adding exceptions // and concurrent CreateExceptionObject() calls do not constitute @@ -2435,7 +2431,7 @@ namespace System.Threading.Tasks /// <param name="delegateRan">Whether the delegate was executed.</param> internal void FinishThreadAbortedTask(bool bTAEAddedToExceptionHolder, bool delegateRan) { - Contract.Assert(!bTAEAddedToExceptionHolder || m_contingentProperties?.m_exceptionsHolder != null, + Debug.Assert(!bTAEAddedToExceptionHolder || m_contingentProperties?.m_exceptionsHolder != null, "FinishThreadAbortedTask() called on a task whose exception holder wasn't initialized"); // this will only be false for non-root self replicating task copies, because all of their exceptions go to the root task. @@ -2671,7 +2667,6 @@ namespace System.Threading.Tasks /// IThreadPoolWorkItem override, which is the entry function for this task when the TP scheduler decides to run it. /// /// </summary> - [SecurityCritical] void IThreadPoolWorkItem.ExecuteWorkItem() { ExecuteEntry(false); @@ -2681,7 +2676,6 @@ namespace System.Threading.Tasks /// The ThreadPool calls this if a ThreadAbortException is thrown while trying to execute this workitem. This may occur /// before Task would otherwise be able to observe it. /// </summary> - [SecurityCritical] void IThreadPoolWorkItem.MarkAborted(ThreadAbortException tae) { // If the task has marked itself as Completed, then it either a) already observed this exception (so we shouldn't handle it here) @@ -2700,7 +2694,6 @@ namespace System.Threading.Tasks /// </summary> /// <param name="bPreventDoubleExecution"> Performs atomic updates to prevent double execution. Should only be set to true /// in codepaths servicing user provided TaskSchedulers. The ConcRT or ThreadPool schedulers don't need this. </param> - [SecuritySafeCritical] internal bool ExecuteEntry(bool bPreventDoubleExecution) { if (bPreventDoubleExecution || ((Options & (TaskCreationOptions)InternalTaskOptions.SelfReplicating) != 0)) @@ -2742,7 +2735,6 @@ namespace System.Threading.Tasks } // A trick so we can refer to the TLS slot with a byref. - [SecurityCritical] private void ExecuteWithThreadLocal(ref Task currentTaskSlot) { // Remember the current task so we can restore it after running, and then @@ -2819,14 +2811,12 @@ namespace System.Threading.Tasks } // Cached callback delegate that's lazily initialized due to ContextCallback being SecurityCritical - [SecurityCritical] private static ContextCallback s_ecCallback; - [SecurityCritical] private static void ExecutionContextCallback(object obj) { Task task = obj as Task; - Contract.Assert(task != null, "expected a task object"); + Debug.Assert(task != null, "expected a task object"); task.Execute(); } @@ -2837,7 +2827,7 @@ namespace System.Threading.Tasks internal virtual void InnerInvoke() { // Invoke the delegate - Contract.Assert(m_action != null, "Null action in InnerInvoke()"); + Debug.Assert(m_action != null, "Null action in InnerInvoke()"); var action = m_action as Action; if (action != null) { @@ -2850,7 +2840,7 @@ namespace System.Threading.Tasks actionWithState(m_stateObject); return; } - Contract.Assert(false, "Invalid m_action in Task"); + Debug.Assert(false, "Invalid m_action in Task"); } /// <summary> @@ -2929,7 +2919,6 @@ namespace System.Threading.Tasks /// <param name="flowExecutionContext">Whether to flow ExecutionContext across the await.</param> /// <param name="stackMark">A stack crawl mark tied to execution context.</param> /// <exception cref="System.InvalidOperationException">The awaiter was not properly initialized.</exception> - [SecurityCritical] internal void SetContinuationForAwait( Action continuationAction, bool continueOnCapturedContext, bool flowExecutionContext, ref StackCrawlMark stackMark) { @@ -2986,7 +2975,7 @@ namespace System.Threading.Tasks } else { - Contract.Assert(!flowExecutionContext, "We already determined we're not required to flow context."); + Debug.Assert(!flowExecutionContext, "We already determined we're not required to flow context."); if (!AddTaskContinuation(continuationAction, addBeforeOthers: false)) AwaitTaskContinuation.UnsafeScheduleAction(continuationAction, this); } @@ -3019,7 +3008,7 @@ namespace System.Threading.Tasks Wait(Timeout.Infinite, default(CancellationToken)); #if DEBUG - Contract.Assert(waitResult, "expected wait to succeed"); + Debug.Assert(waitResult, "expected wait to succeed"); #endif } @@ -3154,7 +3143,7 @@ namespace System.Threading.Tasks ThrowIfExceptional(true); } - Contract.Assert((m_stateFlags & TASK_STATE_FAULTED) == 0, "Task.Wait() completing when in Faulted state."); + Debug.Assert((m_stateFlags & TASK_STATE_FAULTED) == 0, "Task.Wait() completing when in Faulted state."); return true; } @@ -3230,7 +3219,7 @@ namespace System.Threading.Tasks } } - Contract.Assert(IsCompleted || millisecondsTimeout != Timeout.Infinite); + Debug.Assert(IsCompleted || millisecondsTimeout != Timeout.Infinite); // ETW event for Task Wait End if (etwIsEnabled) @@ -3358,7 +3347,6 @@ namespace System.Threading.Tasks /// For custom schedulers we also attempt an atomic state transition. /// </param> /// <returns>true if the task was successfully canceled; otherwise, false.</returns> - [SecuritySafeCritical] internal bool InternalCancel(bool bCancelNonExecutingOnly) { Contract.Requires((Options & (TaskCreationOptions)InternalTaskOptions.PromiseTask) == 0, "Task.InternalCancel() did not expect promise-style task"); @@ -3426,7 +3414,7 @@ namespace System.Threading.Tasks if (bPopSucceeded) { // hitting this would mean something wrong with the AtomicStateUpdate above - Contract.Assert(!mustCleanup, "Possibly an invalid state transition call was made in InternalCancel()"); + Debug.Assert(!mustCleanup, "Possibly an invalid state transition call was made in InternalCancel()"); // Include TASK_STATE_DELEGATE_INVOKED in "illegal" bits to protect against the situation where // TS.TryDequeue() returns true but the task is still left on the queue. @@ -3466,8 +3454,8 @@ namespace System.Threading.Tasks { RecordInternalCancellationRequest(); - Contract.Assert((Options & (TaskCreationOptions)InternalTaskOptions.PromiseTask) != 0, "Task.RecordInternalCancellationRequest(CancellationToken) only valid for promise-style task"); - Contract.Assert(m_contingentProperties.m_cancellationToken == default(CancellationToken)); + Debug.Assert((Options & (TaskCreationOptions)InternalTaskOptions.PromiseTask) != 0, "Task.RecordInternalCancellationRequest(CancellationToken) only valid for promise-style task"); + Debug.Assert(m_contingentProperties.m_cancellationToken == default(CancellationToken)); // Store the supplied cancellation token as this task's token. // Waiting on this task will then result in an OperationCanceledException containing this token. @@ -3492,11 +3480,11 @@ namespace System.Threading.Tasks if (oce == null) { var edi = cancellationException as ExceptionDispatchInfo; - Contract.Assert(edi != null, "Expected either an OCE or an EDI"); + Debug.Assert(edi != null, "Expected either an OCE or an EDI"); oce = edi.SourceException as OperationCanceledException; - Contract.Assert(oce != null, "Expected EDI to contain an OCE"); + Debug.Assert(oce != null, "Expected EDI to contain an OCE"); } - Contract.Assert(oce.CancellationToken == tokenToRecord, + Debug.Assert(oce.CancellationToken == tokenToRecord, "Expected OCE's token to match the provided token."); #endif AddException(cancellationException, representsCancellation: true); @@ -3507,10 +3495,10 @@ namespace System.Threading.Tasks // And this method should be called at most once per task. internal void CancellationCleanupLogic() { - Contract.Assert((m_stateFlags & (TASK_STATE_CANCELED | TASK_STATE_COMPLETION_RESERVED)) != 0, "Task.CancellationCleanupLogic(): Task not canceled or reserved."); + Debug.Assert((m_stateFlags & (TASK_STATE_CANCELED | TASK_STATE_COMPLETION_RESERVED)) != 0, "Task.CancellationCleanupLogic(): Task not canceled or reserved."); // I'd like to do this, but there is a small window for a race condition. If someone calls Wait() between InternalCancel() and // here, that will set m_completionEvent, leading to a meaningless/harmless assertion. - //Contract.Assert((m_completionEvent == null) || !m_completionEvent.IsSet, "Task.CancellationCleanupLogic(): Completion event already set."); + //Debug.Assert((m_completionEvent == null) || !m_completionEvent.IsSet, "Task.CancellationCleanupLogic(): Completion event already set."); // This may have been set already, but we need to make sure. Interlocked.Exchange(ref m_stateFlags, m_stateFlags | TASK_STATE_CANCELED); @@ -3541,8 +3529,8 @@ namespace System.Threading.Tasks /// </summary> private void SetCancellationAcknowledged() { - Contract.Assert(this == Task.InternalCurrent, "SetCancellationAcknowledged() should only be called while this is still the current task"); - Contract.Assert(IsCancellationRequested, "SetCancellationAcknowledged() should not be called if the task's CT wasn't signaled"); + Debug.Assert(this == Task.InternalCurrent, "SetCancellationAcknowledged() should only be called while this is still the current task"); + Debug.Assert(IsCancellationRequested, "SetCancellationAcknowledged() should not be called if the task's CT wasn't signaled"); m_stateFlags |= TASK_STATE_CANCELLATIONACKNOWLEDGED; } @@ -3558,7 +3546,6 @@ namespace System.Threading.Tasks /// <summary> /// Runs all of the continuations, as appropriate. /// </summary> - [SecuritySafeCritical] // for AwaitTaskContinuation.RunOrScheduleAction internal void FinishContinuations() { // Atomically store the fact that this task is completing. From this point on, the adding of continuations will @@ -3684,7 +3671,7 @@ namespace System.Threading.Tasks // Otherwise, it must be an ITaskCompletionAction, so invoke it. else { - Contract.Assert(currentContinuation is ITaskCompletionAction, "Expected continuation element to be Action, TaskContinuation, or ITaskContinuationAction"); + Debug.Assert(currentContinuation is ITaskCompletionAction, "Expected continuation element to be Action, TaskContinuation, or ITaskContinuationAction"); var action = (ITaskCompletionAction)currentContinuation; if (bCanInlineContinuations || !action.InvokeMayRunArbitraryCode) @@ -4730,7 +4717,7 @@ namespace System.Threading.Tasks // m_continuationObject is guaranteed at this point to be either a List or // s_taskCompletionSentinel. List<object> list = m_continuationObject as List<object>; - Contract.Assert((list != null) || (m_continuationObject == s_taskCompletionSentinel), + Debug.Assert((list != null) || (m_continuationObject == s_taskCompletionSentinel), "Expected m_continuationObject to be list or sentinel"); // If list is null, it can only mean that s_taskCompletionSentinel has been exchanged @@ -4873,7 +4860,7 @@ namespace System.Threading.Tasks WaitAll(tasks, Timeout.Infinite); #if DEBUG - Contract.Assert(waitResult, "expected wait to succeed"); + Debug.Assert(waitResult, "expected wait to succeed"); #endif } @@ -5134,7 +5121,7 @@ namespace System.Threading.Tasks // Now gather up and throw all of the exceptions. foreach (var task in tasks) AddExceptionsForCompletedTask(ref exceptions, task); - Contract.Assert(exceptions != null, "Should have seen at least one exception"); + Debug.Assert(exceptions != null, "Should have seen at least one exception"); ThrowHelper.ThrowAggregateException(exceptions); } @@ -5159,8 +5146,8 @@ namespace System.Threading.Tasks /// <returns>true if all of the tasks completed; otherwise, false.</returns> private static bool WaitAllBlockingCore(List<Task> tasks, int millisecondsTimeout, CancellationToken cancellationToken) { - Contract.Assert(tasks != null, "Expected a non-null list of tasks"); - Contract.Assert(tasks.Count > 0, "Expected at least one task"); + Debug.Assert(tasks != null, "Expected a non-null list of tasks"); + Debug.Assert(tasks.Count > 0, "Expected at least one task"); bool waitCompleted = false; var mres = new SetOnCountdownMres(tasks.Count); @@ -5206,14 +5193,14 @@ namespace System.Threading.Tasks internal SetOnCountdownMres(int count) { - Contract.Assert(count > 0, "Expected count > 0"); + Debug.Assert(count > 0, "Expected count > 0"); _count = count; } public void Invoke(Task completingTask) { if (Interlocked.Decrement(ref _count) == 0) Set(); - Contract.Assert(_count >= 0, "Count should never go below 0"); + Debug.Assert(_count >= 0, "Count should never go below 0"); } public bool InvokeMayRunArbitraryCode { get { return false; } } @@ -5304,7 +5291,7 @@ namespace System.Threading.Tasks public static int WaitAny(params Task[] tasks) { int waitResult = WaitAny(tasks, Timeout.Infinite); - Contract.Assert(tasks.Length == 0 || waitResult != -1, "expected wait to succeed"); + Debug.Assert(tasks.Length == 0 || waitResult != -1, "expected wait to succeed"); return waitResult; } @@ -5475,9 +5462,9 @@ namespace System.Threading.Tasks bool waitCompleted = firstCompleted.Wait(millisecondsTimeout, cancellationToken); if (waitCompleted) { - Contract.Assert(firstCompleted.Status == TaskStatus.RanToCompletion); + Debug.Assert(firstCompleted.Status == TaskStatus.RanToCompletion); signaledTaskIndex = Array.IndexOf(tasks, firstCompleted.Result); - Contract.Assert(signaledTaskIndex >= 0); + Debug.Assert(signaledTaskIndex >= 0); } } @@ -5521,7 +5508,7 @@ namespace System.Threading.Tasks var task = new Task<TResult>(); bool succeeded = task.TrySetException(exception); - Contract.Assert(succeeded, "This should always succeed on a new task."); + Debug.Assert(succeeded, "This should always succeed on a new task."); return task; } @@ -5559,7 +5546,7 @@ namespace System.Threading.Tasks var task = new Task<TResult>(); bool succeeded = task.TrySetCanceled(exception.CancellationToken, exception); - Contract.Assert(succeeded, "This should always succeed on a new task."); + Debug.Assert(succeeded, "This should always succeed on a new task."); return task; } @@ -6124,7 +6111,7 @@ namespace System.Threading.Tasks for (int i = 0; i < m_tasks.Length; i++) { var task = m_tasks[i]; - Contract.Assert(task != null, "Constituent task in WhenAll should never be null"); + Debug.Assert(task != null, "Constituent task in WhenAll should never be null"); if (task.IsFaulted) { @@ -6144,7 +6131,7 @@ namespace System.Threading.Tasks if (observedExceptions != null) { - Contract.Assert(observedExceptions.Count > 0, "Expected at least one exception"); + Debug.Assert(observedExceptions.Count > 0, "Expected at least one exception"); //We don't need to TraceOperationCompleted here because TrySetException will call Finish and we'll log it there @@ -6166,7 +6153,7 @@ namespace System.Threading.Tasks TrySetResult(default(VoidTaskResult)); } } - Contract.Assert(m_count >= 0, "Count should never go below 0"); + Debug.Assert(m_count >= 0, "Count should never go below 0"); } public bool InvokeMayRunArbitraryCode { get { return true; } } @@ -6371,7 +6358,7 @@ namespace System.Threading.Tasks for (int i = 0; i < m_tasks.Length; i++) { Task<T> task = m_tasks[i]; - Contract.Assert(task != null, "Constituent task in WhenAll should never be null"); + Debug.Assert(task != null, "Constituent task in WhenAll should never be null"); if (task.IsFaulted) { @@ -6384,7 +6371,7 @@ namespace System.Threading.Tasks } else { - Contract.Assert(task.Status == TaskStatus.RanToCompletion); + Debug.Assert(task.Status == TaskStatus.RanToCompletion); results[i] = task.GetResultCore(waitCompletionNotification: false); // avoid Result, which would triggering debug notification } @@ -6396,7 +6383,7 @@ namespace System.Threading.Tasks if (observedExceptions != null) { - Contract.Assert(observedExceptions.Count > 0, "Expected at least one exception"); + Debug.Assert(observedExceptions.Count > 0, "Expected at least one exception"); //We don't need to TraceOperationCompleted here because TrySetException will call Finish and we'll log it there @@ -6418,7 +6405,7 @@ namespace System.Threading.Tasks TrySetResult(results); } } - Contract.Assert(m_count >= 0, "Count should never go below 0"); + Debug.Assert(m_count >= 0, "Count should never go below 0"); } public bool InvokeMayRunArbitraryCode { get { return true; } } @@ -6612,7 +6599,7 @@ namespace System.Threading.Tasks Task continuationTask = continuationObject as Task; if (continuationTask != null) { - Contract.Assert(continuationTask.m_action == null); + Debug.Assert(continuationTask.m_action == null); Delegate[] delegates = continuationTask.GetDelegateContinuationsForDebugger(); if (delegates != null) return delegates; @@ -6677,13 +6664,11 @@ namespace System.Threading.Tasks m_completingTask = completingTask; } - [SecurityCritical] void IThreadPoolWorkItem.ExecuteWorkItem() { m_action.Invoke(m_completingTask); } - [SecurityCritical] void IThreadPoolWorkItem.MarkAborted(ThreadAbortException tae) { /* NOP */ @@ -6999,25 +6984,12 @@ namespace System.Threading.Tasks // that can SO in 20 inlines on a typical 1MB stack size probably needs to be revisited anyway. private const int MAX_UNCHECKED_INLINING_DEPTH = 20; -#if !FEATURE_CORECLR - - private UInt64 m_lastKnownWatermark; - private static int s_pageSize; - - // We are conservative here. We assume that the platform needs a whole 64KB to - // respond to stack overflow. This means that for very small stacks (e.g. 128KB) - // we'll fail a lot of stack checks incorrectly. - private const long STACK_RESERVED_SPACE = 4096 * 16; - -#endif // !FEATURE_CORECLR - /// <summary> /// This method needs to be called before attempting inline execution on the current thread. /// If false is returned, it means we are too close to the end of the stack and should give up inlining. /// Each call to TryBeginInliningScope() that returns true must be matched with a /// call to EndInliningScope() regardless of whether inlining actually took place. /// </summary> - [SecuritySafeCritical] internal bool TryBeginInliningScope() { // If we're still under the 'safe' limit we'll just skip the stack probe to save p/invoke calls @@ -7037,59 +7009,15 @@ namespace System.Threading.Tasks internal void EndInliningScope() { m_inliningDepth--; - Contract.Assert(m_inliningDepth >= 0, "Inlining depth count should never go negative."); + Debug.Assert(m_inliningDepth >= 0, "Inlining depth count should never go negative."); // do the right thing just in case... if (m_inliningDepth < 0) m_inliningDepth = 0; } - [SecurityCritical] private unsafe bool CheckForSufficientStack() { -#if FEATURE_CORECLR return RuntimeHelpers.TryEnsureSufficientExecutionStack(); -#else - // see if we already have the system page size info recorded - int pageSize = s_pageSize; - if (pageSize == 0) - { - // If not we need to query it from GetSystemInfo() - // Note that this happens only once for the process lifetime - Win32Native.SYSTEM_INFO sysInfo = new Win32Native.SYSTEM_INFO(); - Win32Native.GetSystemInfo(ref sysInfo); - - s_pageSize = pageSize = sysInfo.dwPageSize; - } - - Win32Native.MEMORY_BASIC_INFORMATION stackInfo = new Win32Native.MEMORY_BASIC_INFORMATION(); - - // We subtract one page for our request. VirtualQuery rounds UP to the next page. - // Unfortunately, the stack grows down. If we're on the first page (last page in the - // VirtualAlloc), we'll be moved to the next page, which is off the stack! - - UIntPtr currentAddr = new UIntPtr(&stackInfo - pageSize); - UInt64 current64 = currentAddr.ToUInt64(); - - // Check whether we previously recorded a deeper stack than where we currently are, - // If so we don't need to do the P/Invoke to VirtualQuery - if (m_lastKnownWatermark != 0 && current64 > m_lastKnownWatermark) - return true; - - // Actual stack probe. P/Invoke to query for the current stack allocation information. - Win32Native.VirtualQuery(currentAddr.ToPointer(), ref stackInfo, (UIntPtr)(sizeof(Win32Native.MEMORY_BASIC_INFORMATION))); - - // If the current address minus the base (remember: the stack grows downward in the - // address space) is greater than the number of bytes requested plus the reserved - // space at the end, the request has succeeded. - - if ((current64 - ((UIntPtr)stackInfo.AllocationBase).ToUInt64()) > STACK_RESERVED_SPACE) - { - m_lastKnownWatermark = current64; - return true; - } - - return false; -#endif } } @@ -7204,16 +7132,15 @@ namespace System.Threading.Tasks case STATE_WAITING_ON_INNER_TASK: bool result = TrySetFromTask(completingTask, lookForOce: false); _state = STATE_DONE; // bump the state - Contract.Assert(result, "Expected TrySetFromTask from inner task to succeed"); + Debug.Assert(result, "Expected TrySetFromTask from inner task to succeed"); break; default: - Contract.Assert(false, "UnwrapPromise in illegal state"); + Debug.Assert(false, "UnwrapPromise in illegal state"); break; } } // Calls InvokeCore asynchronously. - [SecuritySafeCritical] private void InvokeCoreAsync(Task completingTask) { // Queue a call to Invoke. If we're so deep on the stack that we're at risk of overflowing, @@ -7233,7 +7160,7 @@ namespace System.Threading.Tasks private void ProcessCompletedOuterTask(Task task) { Contract.Requires(task != null && task.IsCompleted, "Expected non-null, completed outer task"); - Contract.Assert(_state == STATE_WAITING_ON_OUTER_TASK, "We're in the wrong state!"); + Debug.Assert(_state == STATE_WAITING_ON_OUTER_TASK, "We're in the wrong state!"); // Bump our state before proceeding any further _state = STATE_WAITING_ON_INNER_TASK; @@ -7245,7 +7172,7 @@ namespace System.Threading.Tasks case TaskStatus.Canceled: case TaskStatus.Faulted: bool result = TrySetFromTask(task, _lookForOce); - Contract.Assert(result, "Expected TrySetFromTask from outer task to succeed"); + Debug.Assert(result, "Expected TrySetFromTask from outer task to succeed"); break; // Otherwise, process the inner task it returned. diff --git a/src/mscorlib/src/System/Threading/Tasks/TaskCompletionSource.cs b/src/mscorlib/src/System/Threading/Tasks/TaskCompletionSource.cs index 8b1dd2a62f..320f704f09 100644 --- a/src/mscorlib/src/System/Threading/Tasks/TaskCompletionSource.cs +++ b/src/mscorlib/src/System/Threading/Tasks/TaskCompletionSource.cs @@ -12,6 +12,7 @@ // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Collections.Generic; using System.Runtime.CompilerServices; @@ -47,7 +48,6 @@ namespace System.Threading.Tasks /// </remarks> /// <typeparam name="TResult">The type of the result value assocatied with this <see /// cref="TaskCompletionSource{TResult}"/>.</typeparam> - [HostProtection(Synchronization = true, ExternalThreading = true)] public class TaskCompletionSource<TResult> { private readonly Task<TResult> m_task; @@ -209,9 +209,9 @@ namespace System.Threading.Tasks /// <remarks>Unlike the public methods, this method doesn't currently validate that its arguments are correct.</remarks> internal bool TrySetException(IEnumerable<ExceptionDispatchInfo> exceptions) { - Contract.Assert(exceptions != null); + Debug.Assert(exceptions != null); #if DEBUG - foreach(var edi in exceptions) Contract.Assert(edi != null, "Contents must be non-null"); + foreach(var edi in exceptions) Debug.Assert(edi != null, "Contents must be non-null"); #endif bool rval = m_task.TrySetException(exceptions); diff --git a/src/mscorlib/src/System/Threading/Tasks/TaskContinuation.cs b/src/mscorlib/src/System/Threading/Tasks/TaskContinuation.cs index 4c035dfddb..70b9418dbf 100644 --- a/src/mscorlib/src/System/Threading/Tasks/TaskContinuation.cs +++ b/src/mscorlib/src/System/Threading/Tasks/TaskContinuation.cs @@ -11,6 +11,7 @@ // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Security; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.ExceptionServices; using System.Runtime.CompilerServices; @@ -45,7 +46,7 @@ namespace System.Threading.Tasks // Get and null out the antecedent. This is crucial to avoid a memory // leak with long chains of continuations. var antecedent = m_antecedent; - Contract.Assert(antecedent != null, + Debug.Assert(antecedent != null, "No antecedent was set for the ContinuationTaskFromTask."); m_antecedent = null; @@ -53,7 +54,7 @@ namespace System.Threading.Tasks antecedent.NotifyDebuggerOfWaitCompletionIfNecessary(); // Invoke the delegate - Contract.Assert(m_action != null); + Debug.Assert(m_action != null); var action = m_action as Action<Task>; if (action != null) { @@ -66,7 +67,7 @@ namespace System.Threading.Tasks actionWithState(antecedent, m_stateObject); return; } - Contract.Assert(false, "Invalid m_action in ContinuationTaskFromTask"); + Debug.Assert(false, "Invalid m_action in ContinuationTaskFromTask"); } } @@ -93,7 +94,7 @@ namespace System.Threading.Tasks // Get and null out the antecedent. This is crucial to avoid a memory // leak with long chains of continuations. var antecedent = m_antecedent; - Contract.Assert(antecedent != null, + Debug.Assert(antecedent != null, "No antecedent was set for the ContinuationResultTaskFromTask."); m_antecedent = null; @@ -101,7 +102,7 @@ namespace System.Threading.Tasks antecedent.NotifyDebuggerOfWaitCompletionIfNecessary(); // Invoke the delegate - Contract.Assert(m_action != null); + Debug.Assert(m_action != null); var func = m_action as Func<Task, TResult>; if (func != null) { @@ -114,7 +115,7 @@ namespace System.Threading.Tasks m_result = funcWithState(antecedent, m_stateObject); return; } - Contract.Assert(false, "Invalid m_action in ContinuationResultTaskFromTask"); + Debug.Assert(false, "Invalid m_action in ContinuationResultTaskFromTask"); } } @@ -141,7 +142,7 @@ namespace System.Threading.Tasks // Get and null out the antecedent. This is crucial to avoid a memory // leak with long chains of continuations. var antecedent = m_antecedent; - Contract.Assert(antecedent != null, + Debug.Assert(antecedent != null, "No antecedent was set for the ContinuationTaskFromResultTask."); m_antecedent = null; @@ -149,7 +150,7 @@ namespace System.Threading.Tasks antecedent.NotifyDebuggerOfWaitCompletionIfNecessary(); // Invoke the delegate - Contract.Assert(m_action != null); + Debug.Assert(m_action != null); var action = m_action as Action<Task<TAntecedentResult>>; if (action != null) { @@ -162,7 +163,7 @@ namespace System.Threading.Tasks actionWithState(antecedent, m_stateObject); return; } - Contract.Assert(false, "Invalid m_action in ContinuationTaskFromResultTask"); + Debug.Assert(false, "Invalid m_action in ContinuationTaskFromResultTask"); } } @@ -189,7 +190,7 @@ namespace System.Threading.Tasks // Get and null out the antecedent. This is crucial to avoid a memory // leak with long chains of continuations. var antecedent = m_antecedent; - Contract.Assert(antecedent != null, + Debug.Assert(antecedent != null, "No antecedent was set for the ContinuationResultTaskFromResultTask."); m_antecedent = null; @@ -197,7 +198,7 @@ namespace System.Threading.Tasks antecedent.NotifyDebuggerOfWaitCompletionIfNecessary(); // Invoke the delegate - Contract.Assert(m_action != null); + Debug.Assert(m_action != null); var func = m_action as Func<Task<TAntecedentResult>, TResult>; if (func != null) { @@ -210,7 +211,7 @@ namespace System.Threading.Tasks m_result = funcWithState(antecedent, m_stateObject); return; } - Contract.Assert(false, "Invalid m_action in ContinuationResultTaskFromResultTask"); + Debug.Assert(false, "Invalid m_action in ContinuationResultTaskFromResultTask"); } } @@ -235,11 +236,10 @@ namespace System.Threading.Tasks /// <param name="needsProtection"> /// true if we need to protect against multiple threads racing to start/cancel the task; otherwise, false. /// </param> - [SecuritySafeCritical] protected static void InlineIfPossibleOrElseQueue(Task task, bool needsProtection) { Contract.Requires(task != null); - Contract.Assert(task.m_taskScheduler != null); + Debug.Assert(task.m_taskScheduler != null); // Set the TASK_STATE_STARTED flag. This only needs to be done // if the task may be canceled or if someone else has a reference to it @@ -305,7 +305,7 @@ namespace System.Threading.Tasks m_options = options; m_taskScheduler = scheduler; if (AsyncCausalityTracer.LoggingOn) - AsyncCausalityTracer.TraceOperationCreation(CausalityTraceLevel.Required, m_task.Id, "Task.ContinueWith: " + ((Delegate)task.m_action).Method.Name, 0); + AsyncCausalityTracer.TraceOperationCreation(CausalityTraceLevel.Required, m_task.Id, "Task.ContinueWith: " + task.m_action.Method.Name, 0); if (Task.s_asyncDebuggingEnabled) { @@ -318,8 +318,8 @@ namespace System.Threading.Tasks /// <param name="bCanInlineContinuationTask">Whether the continuation can be inlined.</param> internal override void Run(Task completedTask, bool bCanInlineContinuationTask) { - Contract.Assert(completedTask != null); - Contract.Assert(completedTask.IsCompleted, "ContinuationTask.Run(): completedTask not completed"); + Debug.Assert(completedTask != null); + Debug.Assert(completedTask.IsCompleted, "ContinuationTask.Run(): completedTask not completed"); // Check if the completion status of the task works with the desired // activation criteria of the TaskContinuationOptions. @@ -374,7 +374,7 @@ namespace System.Threading.Tasks return m_task.GetDelegateContinuationsForDebugger(); } - return new Delegate[] { m_task.m_action as Delegate }; + return new Delegate[] { m_task.m_action }; } } @@ -384,7 +384,6 @@ namespace System.Threading.Tasks /// <summary>SendOrPostCallback delegate to invoke the action.</summary> private readonly static SendOrPostCallback s_postCallback = state => ((Action)state)(); // can't use InvokeAction as it's SecurityCritical /// <summary>Cached delegate for PostAction</summary> - [SecurityCritical] private static ContextCallback s_postActionCallback; /// <summary>The context with which to run the action.</summary> private readonly SynchronizationContext m_syncContext; @@ -394,19 +393,17 @@ namespace System.Threading.Tasks /// <param name="action">The action to invoke. Must not be null.</param> /// <param name="flowExecutionContext">Whether to capture and restore ExecutionContext.</param> /// <param name="stackMark">The captured stack mark.</param> - [SecurityCritical] internal SynchronizationContextAwaitTaskContinuation( SynchronizationContext context, Action action, bool flowExecutionContext, ref StackCrawlMark stackMark) : base(action, flowExecutionContext, ref stackMark) { - Contract.Assert(context != null); + Debug.Assert(context != null); m_syncContext = context; } /// <summary>Inlines or schedules the continuation.</summary> /// <param name="ignored">The antecedent task, which is ignored.</param> /// <param name="canInlineContinuationTask">true if inlining is permitted; otherwise, false.</param> - [SecuritySafeCritical] internal sealed override void Run(Task task, bool canInlineContinuationTask) { // If we're allowed to inline, run the action on this thread. @@ -431,7 +428,6 @@ namespace System.Threading.Tasks /// <summary>Calls InvokeOrPostAction(false) on the supplied SynchronizationContextAwaitTaskContinuation.</summary> /// <param name="state">The SynchronizationContextAwaitTaskContinuation.</param> - [SecurityCritical] private static void PostAction(object state) { var c = (SynchronizationContextAwaitTaskContinuation)state; @@ -465,7 +461,6 @@ namespace System.Threading.Tasks /// to be passed as state. /// </returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] - [SecurityCritical] private static ContextCallback GetPostActionCallback() { ContextCallback callback = s_postActionCallback; @@ -485,12 +480,11 @@ namespace System.Threading.Tasks /// <param name="action">The action to invoke. Must not be null.</param> /// <param name="flowExecutionContext">Whether to capture and restore ExecutionContext.</param> /// <param name="stackMark">The captured stack mark.</param> - [SecurityCritical] internal TaskSchedulerAwaitTaskContinuation( TaskScheduler scheduler, Action action, bool flowExecutionContext, ref StackCrawlMark stackMark) : base(action, flowExecutionContext, ref stackMark) { - Contract.Assert(scheduler != null); + Debug.Assert(scheduler != null); m_scheduler = scheduler; } @@ -550,7 +544,6 @@ namespace System.Threading.Tasks /// <param name="action">The action to invoke. Must not be null.</param> /// <param name="flowExecutionContext">Whether to capture and restore ExecutionContext.</param> /// <param name="stackMark">The captured stack mark with which to construct an ExecutionContext.</param> - [SecurityCritical] internal AwaitTaskContinuation(Action action, bool flowExecutionContext, ref StackCrawlMark stackMark) { Contract.Requires(action != null); @@ -566,7 +559,6 @@ namespace System.Threading.Tasks /// <summary>Initializes the continuation.</summary> /// <param name="action">The action to invoke. Must not be null.</param> /// <param name="flowExecutionContext">Whether to capture and restore ExecutionContext.</param> - [SecurityCritical] internal AwaitTaskContinuation(Action action, bool flowExecutionContext) { Contract.Requires(action != null); @@ -598,7 +590,6 @@ namespace System.Threading.Tasks /// <summary>Inlines or schedules the continuation onto the default scheduler.</summary> /// <param name="ignored">The antecedent task, which is ignored.</param> /// <param name="canInlineContinuationTask">true if inlining is permitted; otherwise, false.</param> - [SecuritySafeCritical] internal override void Run(Task task, bool canInlineContinuationTask) { // For the base AwaitTaskContinuation, we allow inlining if our caller allows it @@ -657,7 +648,6 @@ namespace System.Threading.Tasks } /// <summary>IThreadPoolWorkItem override, which is the entry function for this when the ThreadPool scheduler decides to run it.</summary> - [SecurityCritical] void ExecuteWorkItemHelper() { var etwLog = TplEtwProvider.Log; @@ -696,7 +686,6 @@ namespace System.Threading.Tasks } } - [SecurityCritical] void IThreadPoolWorkItem.ExecuteWorkItem() { // inline the fast path @@ -714,20 +703,16 @@ namespace System.Threading.Tasks /// <summary> /// The ThreadPool calls this if a ThreadAbortException is thrown while trying to execute this workitem. /// </summary> - [SecurityCritical] void IThreadPoolWorkItem.MarkAborted(ThreadAbortException tae) { /* nop */ } /// <summary>Cached delegate that invokes an Action passed as an object parameter.</summary> - [SecurityCritical] private static ContextCallback s_invokeActionCallback; /// <summary>Runs an action provided as an object parameter.</summary> /// <param name="state">The Action to invoke.</param> - [SecurityCritical] private static void InvokeAction(object state) { ((Action)state)(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] - [SecurityCritical] protected static ContextCallback GetInvokeActionCallback() { ContextCallback callback = s_invokeActionCallback; @@ -739,11 +724,10 @@ namespace System.Threading.Tasks /// <param name="callback">The callback to run.</param> /// <param name="state">The state to pass to the callback.</param> /// <param name="currentTask">A reference to Task.t_currentTask.</param> - [SecurityCritical] protected void RunCallback(ContextCallback callback, object state, ref Task currentTask) { Contract.Requires(callback != null); - Contract.Assert(currentTask == Task.t_currentTask); + Debug.Assert(currentTask == Task.t_currentTask); // Pretend there's no current task, so that no task is seen as a parent // and TaskScheduler.Current does not reflect false information @@ -787,10 +771,9 @@ namespace System.Threading.Tasks /// only happens in Task.SetContinuationForAwait if execution context flow was disabled /// via using TaskAwaiter.UnsafeOnCompleted or a similar path. /// </remarks> - [SecurityCritical] internal static void RunOrScheduleAction(Action action, bool allowInlining, ref Task currentTask) { - Contract.Assert(currentTask == Task.t_currentTask); + Debug.Assert(currentTask == Task.t_currentTask); // If we're not allowed to run here, schedule the action if (!allowInlining || !IsValidLocationForInlining) @@ -818,7 +801,6 @@ namespace System.Threading.Tasks /// <summary>Schedules the action to be executed. No ExecutionContext work is performed used.</summary> /// <param name="action">The action to invoke or queue.</param> - [SecurityCritical] internal static void UnsafeScheduleAction(Action action, Task task) { AwaitTaskContinuation atc = new AwaitTaskContinuation(action, flowExecutionContext: false); @@ -859,7 +841,7 @@ namespace System.Threading.Tasks internal override Delegate[] GetDelegateContinuationsForDebugger() { - Contract.Assert(m_action != null); + Debug.Assert(m_action != null); return new Delegate[] { AsyncMethodBuilderCore.TryGetStateMachineForDebugger(m_action) }; } } diff --git a/src/mscorlib/src/System/Threading/Tasks/TaskExceptionHolder.cs b/src/mscorlib/src/System/Threading/Tasks/TaskExceptionHolder.cs index 198db8e15c..45817dab23 100644 --- a/src/mscorlib/src/System/Threading/Tasks/TaskExceptionHolder.cs +++ b/src/mscorlib/src/System/Threading/Tasks/TaskExceptionHolder.cs @@ -18,6 +18,7 @@ namespace System.Threading.Tasks using System; using System.Collections.Generic; using System.Collections.ObjectModel; + using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.ExceptionServices; using System.Security; @@ -62,14 +63,9 @@ namespace System.Threading.Tasks EnsureADUnloadCallbackRegistered(); } - [SecuritySafeCritical] private static bool ShouldFailFastOnUnobservedException() { - bool shouldFailFast = false; - #if !FEATURE_CORECLR - shouldFailFast = System.CLRConfig.CheckThrowUnobservedTaskExceptions(); - #endif - return shouldFailFast; + return false; } private static void EnsureADUnloadCallbackRegistered() @@ -202,12 +198,12 @@ namespace System.Threading.Tasks { Contract.Requires(exceptionObject != null, "Expected exceptionObject to be non-null."); - Contract.Assert(m_cancellationException == 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. - Contract.Assert(m_faultExceptions == null, + 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. @@ -221,7 +217,7 @@ namespace System.Threading.Tasks else { var edi = exceptionObject as ExceptionDispatchInfo; - Contract.Assert(edi != null && edi.SourceException is OperationCanceledException, + Debug.Assert(edi != null && edi.SourceException is OperationCanceledException, "Expected an OCE or an EDI that contained an OCE"); m_cancellationException = edi; } @@ -242,7 +238,7 @@ namespace System.Threading.Tasks // Initialize the exceptions list if necessary. The list should be non-null iff it contains exceptions. var exceptions = m_faultExceptions; if (exceptions == null) m_faultExceptions = exceptions = new List<ExceptionDispatchInfo>(1); - else Contract.Assert(exceptions.Count > 0, "Expected existing exceptions list to have > 0 exceptions."); + else Debug.Assert(exceptions.Count > 0, "Expected existing exceptions list to have > 0 exceptions."); // Handle Exception by capturing it into an ExceptionDispatchInfo and storing that var exception = exceptionObject as Exception; @@ -270,13 +266,13 @@ namespace System.Threading.Tasks foreach (var exc in exColl) { #if DEBUG - Contract.Assert(exc != null, "No exceptions should be null"); + Debug.Assert(exc != null, "No exceptions should be null"); numExceptions++; #endif exceptions.Add(ExceptionDispatchInfo.Capture(exc)); } #if DEBUG - Contract.Assert(numExceptions > 0, "Collection should contain at least one exception."); + Debug.Assert(numExceptions > 0, "Collection should contain at least one exception."); #endif } else @@ -287,17 +283,17 @@ namespace System.Threading.Tasks { exceptions.AddRange(ediColl); #if DEBUG - Contract.Assert(exceptions.Count > 0, "There should be at least one dispatch info."); + Debug.Assert(exceptions.Count > 0, "There should be at least one dispatch info."); foreach(var tmp in exceptions) { - Contract.Assert(tmp != null, "No dispatch infos should be null"); + Debug.Assert(tmp != null, "No dispatch infos should be null"); } #endif } // Anything else is a programming error else { - throw new ArgumentException(Environment.GetResourceString("TaskExceptionHolder_UnknownExceptionType"), "exceptionObject"); + throw new ArgumentException(Environment.GetResourceString("TaskExceptionHolder_UnknownExceptionType"), nameof(exceptionObject)); } } } @@ -370,8 +366,8 @@ namespace System.Threading.Tasks internal AggregateException CreateExceptionObject(bool calledFromFinalizer, Exception includeThisException) { var exceptions = m_faultExceptions; - Contract.Assert(exceptions != null, "Expected an initialized list."); - Contract.Assert(exceptions.Count > 0, "Expected at least one exception."); + Debug.Assert(exceptions != null, "Expected an initialized list."); + Debug.Assert(exceptions.Count > 0, "Expected at least one exception."); // Mark as handled and aggregate the exceptions. MarkAsHandled(calledFromFinalizer); @@ -400,8 +396,8 @@ namespace System.Threading.Tasks internal ReadOnlyCollection<ExceptionDispatchInfo> GetExceptionDispatchInfos() { var exceptions = m_faultExceptions; - Contract.Assert(exceptions != null, "Expected an initialized list."); - Contract.Assert(exceptions.Count > 0, "Expected at least one exception."); + Debug.Assert(exceptions != null, "Expected an initialized list."); + Debug.Assert(exceptions.Count > 0, "Expected at least one exception."); MarkAsHandled(false); return new ReadOnlyCollection<ExceptionDispatchInfo>(exceptions); } @@ -416,7 +412,7 @@ namespace System.Threading.Tasks internal ExceptionDispatchInfo GetCancellationExceptionDispatchInfo() { var edi = m_cancellationException; - Contract.Assert(edi == null || edi.SourceException is OperationCanceledException, + Debug.Assert(edi == null || edi.SourceException is OperationCanceledException, "Expected the EDI to be for an OperationCanceledException"); return edi; } diff --git a/src/mscorlib/src/System/Threading/Tasks/TaskFactory.cs b/src/mscorlib/src/System/Threading/Tasks/TaskFactory.cs index 52b471628a..aa4c2df74b 100644 --- a/src/mscorlib/src/System/Threading/Tasks/TaskFactory.cs +++ b/src/mscorlib/src/System/Threading/Tasks/TaskFactory.cs @@ -18,6 +18,7 @@ using System.Security; using System.Security.Permissions; using System.Runtime.CompilerServices; using System.Threading; +using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.Threading.Tasks @@ -37,7 +38,6 @@ namespace System.Threading.Tasks /// <see cref="System.Threading.Tasks.Task.Factory">Task.Factory</see> property. /// </para> /// </remarks> - [HostProtection(Synchronization = true, ExternalThreading = true)] public class TaskFactory { // member variables @@ -225,7 +225,7 @@ namespace System.Threading.Tasks TaskCreationOptions.PreferFairness | TaskCreationOptions.RunContinuationsAsynchronously)) != 0) { - throw new ArgumentOutOfRangeException("creationOptions"); + throw new ArgumentOutOfRangeException(nameof(creationOptions)); } Contract.EndContractBlock(); } @@ -1593,9 +1593,9 @@ namespace System.Threading.Tasks { // Options detected here cause exceptions in FromAsync methods that take beginMethod as a parameter if ((creationOptions & TaskCreationOptions.LongRunning) != 0) - throw new ArgumentOutOfRangeException("creationOptions", Environment.GetResourceString("Task_FromAsync_LongRunning")); + throw new ArgumentOutOfRangeException(nameof(creationOptions), Environment.GetResourceString("Task_FromAsync_LongRunning")); if ((creationOptions & TaskCreationOptions.PreferFairness) != 0) - throw new ArgumentOutOfRangeException("creationOptions", Environment.GetResourceString("Task_FromAsync_PreferFairness")); + throw new ArgumentOutOfRangeException(nameof(creationOptions), Environment.GetResourceString("Task_FromAsync_PreferFairness")); } // Check for general validity of options @@ -1606,7 +1606,7 @@ namespace System.Threading.Tasks TaskCreationOptions.PreferFairness | TaskCreationOptions.LongRunning)) != 0) { - throw new ArgumentOutOfRangeException("creationOptions"); + throw new ArgumentOutOfRangeException(nameof(creationOptions)); } } @@ -1666,7 +1666,7 @@ namespace System.Threading.Tasks TrySetResult(_tasks); } - Contract.Assert(_count >= 0, "Count should never go below 0"); + Debug.Assert(_count >= 0, "Count should never go below 0"); } public bool InvokeMayRunArbitraryCode { get { return true; } } @@ -1746,7 +1746,7 @@ namespace System.Threading.Tasks TrySetResult(_tasks); } - Contract.Assert(_count >= 0, "Count should never go below 0"); + Debug.Assert(_count >= 0, "Count should never go below 0"); } public bool InvokeMayRunArbitraryCode { get { return true; } } @@ -1801,7 +1801,7 @@ namespace System.Threading.Tasks [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable public Task ContinueWhenAll(Task[] tasks, Action<Task[]> continuationAction) { - if (continuationAction == null) throw new ArgumentNullException("continuationAction"); + if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); Contract.EndContractBlock(); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; @@ -1833,7 +1833,7 @@ namespace System.Threading.Tasks [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable public Task ContinueWhenAll(Task[] tasks, Action<Task[]> continuationAction, CancellationToken cancellationToken) { - if (continuationAction == null) throw new ArgumentNullException("continuationAction"); + if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); Contract.EndContractBlock(); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; @@ -1870,7 +1870,7 @@ namespace System.Threading.Tasks [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable public Task ContinueWhenAll(Task[] tasks, Action<Task[]> continuationAction, TaskContinuationOptions continuationOptions) { - if (continuationAction == null) throw new ArgumentNullException("continuationAction"); + if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); Contract.EndContractBlock(); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; @@ -1918,7 +1918,7 @@ namespace System.Threading.Tasks public Task ContinueWhenAll(Task[] tasks, Action<Task[]> continuationAction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { - if (continuationAction == null) throw new ArgumentNullException("continuationAction"); + if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); Contract.EndContractBlock(); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; @@ -1945,7 +1945,7 @@ namespace System.Threading.Tasks [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable public Task ContinueWhenAll<TAntecedentResult>(Task<TAntecedentResult>[] tasks, Action<Task<TAntecedentResult>[]> continuationAction) { - if (continuationAction == null) throw new ArgumentNullException("continuationAction"); + if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); Contract.EndContractBlock(); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; @@ -1979,7 +1979,7 @@ namespace System.Threading.Tasks public Task ContinueWhenAll<TAntecedentResult>(Task<TAntecedentResult>[] tasks, Action<Task<TAntecedentResult>[]> continuationAction, CancellationToken cancellationToken) { - if (continuationAction == null) throw new ArgumentNullException("continuationAction"); + if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); Contract.EndContractBlock(); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; @@ -2018,7 +2018,7 @@ namespace System.Threading.Tasks public Task ContinueWhenAll<TAntecedentResult>(Task<TAntecedentResult>[] tasks, Action<Task<TAntecedentResult>[]> continuationAction, TaskContinuationOptions continuationOptions) { - if (continuationAction == null) throw new ArgumentNullException("continuationAction"); + if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); Contract.EndContractBlock(); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; @@ -2067,7 +2067,7 @@ namespace System.Threading.Tasks public Task ContinueWhenAll<TAntecedentResult>(Task<TAntecedentResult>[] tasks, Action<Task<TAntecedentResult>[]> continuationAction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { - if (continuationAction == null) throw new ArgumentNullException("continuationAction"); + if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); Contract.EndContractBlock(); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; @@ -2097,7 +2097,7 @@ namespace System.Threading.Tasks [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable public Task<TResult> ContinueWhenAll<TResult>(Task[] tasks, Func<Task[], TResult> continuationFunction) { - if (continuationFunction == null) throw new ArgumentNullException("continuationFunction"); + if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction)); Contract.EndContractBlock(); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; @@ -2133,7 +2133,7 @@ namespace System.Threading.Tasks [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable public Task<TResult> ContinueWhenAll<TResult>(Task[] tasks, Func<Task[], TResult> continuationFunction, CancellationToken cancellationToken) { - if (continuationFunction == null) throw new ArgumentNullException("continuationFunction"); + if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction)); Contract.EndContractBlock(); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; @@ -2174,7 +2174,7 @@ namespace System.Threading.Tasks [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable public Task<TResult> ContinueWhenAll<TResult>(Task[] tasks, Func<Task[], TResult> continuationFunction, TaskContinuationOptions continuationOptions) { - if (continuationFunction == null) throw new ArgumentNullException("continuationFunction"); + if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction)); Contract.EndContractBlock(); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; @@ -2226,7 +2226,7 @@ namespace System.Threading.Tasks public Task<TResult> ContinueWhenAll<TResult>(Task[] tasks, Func<Task[], TResult> continuationFunction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { - if (continuationFunction == null) throw new ArgumentNullException("continuationFunction"); + if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction)); Contract.EndContractBlock(); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; @@ -2258,7 +2258,7 @@ namespace System.Threading.Tasks [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable public Task<TResult> ContinueWhenAll<TAntecedentResult, TResult>(Task<TAntecedentResult>[] tasks, Func<Task<TAntecedentResult>[], TResult> continuationFunction) { - if (continuationFunction == null) throw new ArgumentNullException("continuationFunction"); + if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction)); Contract.EndContractBlock(); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; @@ -2295,7 +2295,7 @@ namespace System.Threading.Tasks public Task<TResult> ContinueWhenAll<TAntecedentResult, TResult>(Task<TAntecedentResult>[] tasks, Func<Task<TAntecedentResult>[], TResult> continuationFunction, CancellationToken cancellationToken) { - if (continuationFunction == null) throw new ArgumentNullException("continuationFunction"); + if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction)); Contract.EndContractBlock(); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; @@ -2338,7 +2338,7 @@ namespace System.Threading.Tasks public Task<TResult> ContinueWhenAll<TAntecedentResult, TResult>(Task<TAntecedentResult>[] tasks, Func<Task<TAntecedentResult>[], TResult> continuationFunction, TaskContinuationOptions continuationOptions) { - if (continuationFunction == null) throw new ArgumentNullException("continuationFunction"); + if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction)); Contract.EndContractBlock(); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; @@ -2391,7 +2391,7 @@ namespace System.Threading.Tasks public Task<TResult> ContinueWhenAll<TAntecedentResult, TResult>(Task<TAntecedentResult>[] tasks, Func<Task<TAntecedentResult>[], TResult> continuationFunction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { - if (continuationFunction == null) throw new ArgumentNullException("continuationFunction"); + if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction)); Contract.EndContractBlock(); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; @@ -2448,7 +2448,7 @@ namespace System.Threading.Tasks } bool success = TrySetResult(completingTask); - Contract.Assert(success, "Only one task should have gotten to this point, and thus this must be successful."); + Debug.Assert(success, "Only one task should have gotten to this point, and thus this must be successful."); // We need to remove continuations that may be left straggling on other tasks. // Otherwise, repeated calls to WhenAny using the same task could leak actions. @@ -2489,7 +2489,7 @@ namespace System.Threading.Tasks for(int i=0; i<numTasks; i++) { var task = tasks[i]; - if (task == null) throw new ArgumentException(Environment.GetResourceString("Task_MultiTaskContinuation_NullTask"), "tasks"); + if (task == null) throw new ArgumentException(Environment.GetResourceString("Task_MultiTaskContinuation_NullTask"), nameof(tasks)); if (checkArgsOnly) continue; @@ -2531,7 +2531,7 @@ namespace System.Threading.Tasks [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable public Task ContinueWhenAny(Task[] tasks, Action<Task> continuationAction) { - if (continuationAction == null) throw new ArgumentNullException("continuationAction"); + if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); Contract.EndContractBlock(); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; @@ -2562,7 +2562,7 @@ namespace System.Threading.Tasks [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable public Task ContinueWhenAny(Task[] tasks, Action<Task> continuationAction, CancellationToken cancellationToken) { - if (continuationAction == null) throw new ArgumentNullException("continuationAction"); + if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); Contract.EndContractBlock(); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; @@ -2599,7 +2599,7 @@ namespace System.Threading.Tasks [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable public Task ContinueWhenAny(Task[] tasks, Action<Task> continuationAction, TaskContinuationOptions continuationOptions) { - if (continuationAction == null) throw new ArgumentNullException("continuationAction"); + if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); Contract.EndContractBlock(); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; @@ -2647,7 +2647,7 @@ namespace System.Threading.Tasks public Task ContinueWhenAny(Task[] tasks, Action<Task> continuationAction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { - if (continuationAction == null) throw new ArgumentNullException("continuationAction"); + if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); Contract.EndContractBlock(); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; @@ -2678,7 +2678,7 @@ namespace System.Threading.Tasks [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable public Task<TResult> ContinueWhenAny<TResult>(Task[] tasks, Func<Task, TResult> continuationFunction) { - if (continuationFunction == null) throw new ArgumentNullException("continuationFunction"); + if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction)); Contract.EndContractBlock(); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; @@ -2713,7 +2713,7 @@ namespace System.Threading.Tasks [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable public Task<TResult> ContinueWhenAny<TResult>(Task[] tasks, Func<Task, TResult> continuationFunction, CancellationToken cancellationToken) { - if (continuationFunction == null) throw new ArgumentNullException("continuationFunction"); + if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction)); Contract.EndContractBlock(); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; @@ -2754,7 +2754,7 @@ namespace System.Threading.Tasks [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable public Task<TResult> ContinueWhenAny<TResult>(Task[] tasks, Func<Task, TResult> continuationFunction, TaskContinuationOptions continuationOptions) { - if (continuationFunction == null) throw new ArgumentNullException("continuationFunction"); + if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction)); Contract.EndContractBlock(); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; @@ -2806,7 +2806,7 @@ namespace System.Threading.Tasks public Task<TResult> ContinueWhenAny<TResult>(Task[] tasks, Func<Task, TResult> continuationFunction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { - if (continuationFunction == null) throw new ArgumentNullException("continuationFunction"); + if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction)); Contract.EndContractBlock(); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; @@ -2838,7 +2838,7 @@ namespace System.Threading.Tasks public Task<TResult> ContinueWhenAny<TAntecedentResult, TResult>(Task<TAntecedentResult>[] tasks, Func<Task<TAntecedentResult>, TResult> continuationFunction) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - if (continuationFunction == null) throw new ArgumentNullException("continuationFunction"); + if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction)); return TaskFactory<TResult>.ContinueWhenAnyImpl<TAntecedentResult>(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler, ref stackMark); } @@ -2872,7 +2872,7 @@ namespace System.Threading.Tasks public Task<TResult> ContinueWhenAny<TAntecedentResult, TResult>(Task<TAntecedentResult>[] tasks, Func<Task<TAntecedentResult>, TResult> continuationFunction, CancellationToken cancellationToken) { - if (continuationFunction == null) throw new ArgumentNullException("continuationFunction"); + if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction)); Contract.EndContractBlock(); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; @@ -2915,7 +2915,7 @@ namespace System.Threading.Tasks public Task<TResult> ContinueWhenAny<TAntecedentResult, TResult>(Task<TAntecedentResult>[] tasks, Func<Task<TAntecedentResult>, TResult> continuationFunction, TaskContinuationOptions continuationOptions) { - if (continuationFunction == null) throw new ArgumentNullException("continuationFunction"); + if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction)); Contract.EndContractBlock(); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; @@ -2968,7 +2968,7 @@ namespace System.Threading.Tasks public Task<TResult> ContinueWhenAny<TAntecedentResult, TResult>(Task<TAntecedentResult>[] tasks, Func<Task<TAntecedentResult>, TResult> continuationFunction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { - if (continuationFunction == null) throw new ArgumentNullException("continuationFunction"); + if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction)); Contract.EndContractBlock(); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; @@ -2996,7 +2996,7 @@ namespace System.Threading.Tasks [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable public Task ContinueWhenAny<TAntecedentResult>(Task<TAntecedentResult>[] tasks, Action<Task<TAntecedentResult>> continuationAction) { - if (continuationAction == null) throw new ArgumentNullException("continuationAction"); + if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); Contract.EndContractBlock(); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; @@ -3029,7 +3029,7 @@ namespace System.Threading.Tasks public Task ContinueWhenAny<TAntecedentResult>(Task<TAntecedentResult>[] tasks, Action<Task<TAntecedentResult>> continuationAction, CancellationToken cancellationToken) { - if (continuationAction == null) throw new ArgumentNullException("continuationAction"); + if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); Contract.EndContractBlock(); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; @@ -3068,7 +3068,7 @@ namespace System.Threading.Tasks public Task ContinueWhenAny<TAntecedentResult>(Task<TAntecedentResult>[] tasks, Action<Task<TAntecedentResult>> continuationAction, TaskContinuationOptions continuationOptions) { - if (continuationAction == null) throw new ArgumentNullException("continuationAction"); + if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); Contract.EndContractBlock(); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; @@ -3117,7 +3117,7 @@ namespace System.Threading.Tasks public Task ContinueWhenAny<TAntecedentResult>(Task<TAntecedentResult>[] tasks, Action<Task<TAntecedentResult>> continuationAction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { - if (continuationAction == null) throw new ArgumentNullException("continuationAction"); + if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); Contract.EndContractBlock(); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; @@ -3129,9 +3129,9 @@ namespace System.Threading.Tasks internal static Task[] CheckMultiContinuationTasksAndCopy(Task[] tasks) { if (tasks == null) - throw new ArgumentNullException("tasks"); + throw new ArgumentNullException(nameof(tasks)); if (tasks.Length == 0) - throw new ArgumentException(Environment.GetResourceString("Task_MultiTaskContinuation_EmptyTaskList"), "tasks"); + throw new ArgumentException(Environment.GetResourceString("Task_MultiTaskContinuation_EmptyTaskList"), nameof(tasks)); Contract.EndContractBlock(); Task[] tasksCopy = new Task[tasks.Length]; @@ -3140,7 +3140,7 @@ namespace System.Threading.Tasks tasksCopy[i] = tasks[i]; if (tasksCopy[i] == null) - throw new ArgumentException(Environment.GetResourceString("Task_MultiTaskContinuation_NullTask"), "tasks"); + throw new ArgumentException(Environment.GetResourceString("Task_MultiTaskContinuation_NullTask"), nameof(tasks)); } return tasksCopy; @@ -3149,9 +3149,9 @@ namespace System.Threading.Tasks internal static Task<TResult>[] CheckMultiContinuationTasksAndCopy<TResult>(Task<TResult>[] tasks) { if (tasks == null) - throw new ArgumentNullException("tasks"); + throw new ArgumentNullException(nameof(tasks)); if (tasks.Length == 0) - throw new ArgumentException(Environment.GetResourceString("Task_MultiTaskContinuation_EmptyTaskList"), "tasks"); + throw new ArgumentException(Environment.GetResourceString("Task_MultiTaskContinuation_EmptyTaskList"), nameof(tasks)); Contract.EndContractBlock(); Task<TResult>[] tasksCopy = new Task<TResult>[tasks.Length]; @@ -3160,7 +3160,7 @@ namespace System.Threading.Tasks tasksCopy[i] = tasks[i]; if (tasksCopy[i] == null) - throw new ArgumentException(Environment.GetResourceString("Task_MultiTaskContinuation_NullTask"), "tasks"); + throw new ArgumentException(Environment.GetResourceString("Task_MultiTaskContinuation_NullTask"), nameof(tasks)); } return tasksCopy; @@ -3179,7 +3179,7 @@ namespace System.Threading.Tasks const TaskContinuationOptions illegalMask = TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.LongRunning; if ((continuationOptions & illegalMask) == illegalMask) { - throw new ArgumentOutOfRangeException("continuationOptions", Environment.GetResourceString("Task_ContinueWith_ESandLR")); + throw new ArgumentOutOfRangeException(nameof(continuationOptions), Environment.GetResourceString("Task_ContinueWith_ESandLR")); } // Check that no nonsensical options are specified. @@ -3193,12 +3193,12 @@ namespace System.Threading.Tasks NotOnAny | TaskContinuationOptions.ExecuteSynchronously)) != 0) { - throw new ArgumentOutOfRangeException("continuationOptions"); + throw new ArgumentOutOfRangeException(nameof(continuationOptions)); } // Check that no "fire" options are specified. if ((continuationOptions & NotOnAny) != 0) - throw new ArgumentOutOfRangeException("continuationOptions", Environment.GetResourceString("Task_MultiTaskContinuation_FireOptions")); + throw new ArgumentOutOfRangeException(nameof(continuationOptions), Environment.GetResourceString("Task_MultiTaskContinuation_FireOptions")); Contract.EndContractBlock(); } } diff --git a/src/mscorlib/src/System/Threading/Tasks/TaskScheduler.cs b/src/mscorlib/src/System/Threading/Tasks/TaskScheduler.cs index f82492499c..fad3fc06c5 100644 --- a/src/mscorlib/src/System/Threading/Tasks/TaskScheduler.cs +++ b/src/mscorlib/src/System/Threading/Tasks/TaskScheduler.cs @@ -41,10 +41,6 @@ namespace System.Threading.Tasks /// </remarks> [DebuggerDisplay("Id={Id}")] [DebuggerTypeProxy(typeof(SystemThreadingTasks_TaskSchedulerDebugView))] - [HostProtection(Synchronization = true, ExternalThreading = true)] -#pragma warning disable 618 - [PermissionSet(SecurityAction.InheritanceDemand, Unrestricted = true)] -#pragma warning restore 618 public abstract class TaskScheduler { //////////////////////////////////////////////////////////// @@ -70,7 +66,6 @@ namespace System.Threading.Tasks /// </remarks> /// <param name="task">The <see cref="T:System.Threading.Tasks.Task">Task</see> to be queued.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="task"/> argument is null.</exception> - [SecurityCritical] protected internal abstract void QueueTask(Task task); /// <summary> @@ -113,7 +108,6 @@ namespace System.Threading.Tasks /// null.</exception> /// <exception cref="T:System.InvalidOperationException">The <paramref name="task"/> was already /// executed.</exception> - [SecurityCritical] protected abstract bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued); /// <summary> @@ -157,7 +151,6 @@ namespace System.Threading.Tasks /// <exception cref="T:System.NotSupportedException"> /// This scheduler is unable to generate a list of queued tasks at this time. /// </exception> - [SecurityCritical] protected abstract IEnumerable<Task> GetScheduledTasks(); /// <summary> @@ -185,7 +178,6 @@ namespace System.Threading.Tasks /// <param name="taskWasPreviouslyQueued">True if the task may have been previously queued, /// false if the task was absolutely not previously queued.</param> /// <returns>True if it ran, false otherwise.</returns> - [SecuritySafeCritical] internal bool TryRunInline(Task task, bool taskWasPreviouslyQueued) { // Do not inline unstarted tasks (i.e., task.ExecutingTaskScheduler == null). @@ -237,7 +229,6 @@ namespace System.Threading.Tasks /// <param name="task">The <see cref="T:System.Threading.Tasks.Task">Task</see> to be dequeued.</param> /// <returns>A Boolean denoting whether the <paramref name="task"/> argument was successfully dequeued.</returns> /// <exception cref="T:System.ArgumentNullException">The <paramref name="task"/> argument is null.</exception> - [SecurityCritical] protected internal virtual bool TryDequeue(Task task) { return false; @@ -262,7 +253,6 @@ namespace System.Threading.Tasks /// <summary> /// Calls QueueTask() after performing any needed firing of events /// </summary> - [SecurityCritical] internal void InternalQueueTask(Task task) { Contract.Requires(task != null); @@ -444,7 +434,6 @@ namespace System.Threading.Tasks /// <returns>A Boolean that is true if <paramref name="task"/> was successfully executed, false if it /// was not. A common reason for execution failure is that the task had previously been executed or /// is in the process of being executed by another thread.</returns> - [SecurityCritical] protected bool TryExecuteTask(Task task) { if (task.ExecutingTaskScheduler != this) @@ -475,7 +464,6 @@ namespace System.Threading.Tasks /// </remarks> public static event EventHandler<UnobservedTaskExceptionEventArgs> UnobservedTaskException { - [System.Security.SecurityCritical] add { if (value != null) @@ -485,7 +473,6 @@ namespace System.Threading.Tasks } } - [System.Security.SecurityCritical] remove { lock (_unobservedTaskExceptionLockObject) _unobservedTaskException -= value; @@ -531,7 +518,6 @@ namespace System.Threading.Tasks /// <exception cref="T:System.NotSupportedException"> /// This scheduler is unable to generate a list of queued tasks at this time. /// </exception> - [SecurityCritical] internal Task[] GetScheduledTasksForDebugger() { // this can throw InvalidOperationException indicating that they are unable to provide the info @@ -566,7 +552,6 @@ namespace System.Threading.Tasks /// It should not be called by any other codepaths. /// </remarks> /// <returns>An array of <see cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see> instances.</returns> - [SecurityCritical] internal static TaskScheduler[] GetTaskSchedulersForDebugger() { if (s_activeTaskSchedulers == null) @@ -587,7 +572,7 @@ namespace System.Threading.Tasks schedulers.CopyTo(arr, 0); foreach (var scheduler in arr) { - Contract.Assert(scheduler != null, "Table returned an incorrect Count or CopyTo failed"); + Debug.Assert(scheduler != null, "Table returned an incorrect Count or CopyTo failed"); int tmp = scheduler.Id; // force Ids for debugger } return arr; @@ -613,7 +598,6 @@ namespace System.Threading.Tasks // returns the scheduler’s GetScheduledTasks public IEnumerable<Task> ScheduledTasks { - [SecurityCritical] get { return m_taskScheduler.GetScheduledTasks(); } } } @@ -656,7 +640,6 @@ namespace System.Threading.Tasks /// Simply posts the tasks to be executed on the associated <see cref="T:System.Threading.SynchronizationContext"/>. /// </summary> /// <param name="task"></param> - [SecurityCritical] protected internal override void QueueTask(Task task) { m_synchronizationContext.Post(s_postCallback, (object)task); @@ -670,7 +653,6 @@ namespace System.Threading.Tasks /// </summary> /// <param name="task"></param> /// <param name="taskWasPreviouslyQueued"></param> - [SecurityCritical] protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { if (SynchronizationContext.Current == m_synchronizationContext) @@ -682,7 +664,6 @@ namespace System.Threading.Tasks } // not implemented - [SecurityCritical] protected override IEnumerable<Task> GetScheduledTasks() { return null; diff --git a/src/mscorlib/src/System/Threading/Tasks/TaskToApm.cs b/src/mscorlib/src/System/Threading/Tasks/TaskToApm.cs index 02b130c297..90743aeec5 100644 --- a/src/mscorlib/src/System/Threading/Tasks/TaskToApm.cs +++ b/src/mscorlib/src/System/Threading/Tasks/TaskToApm.cs @@ -22,6 +22,7 @@ // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.IO; +using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.Threading.Tasks @@ -76,7 +77,7 @@ namespace System.Threading.Tasks if (twar != null) { task = twar.Task; - Contract.Assert(task != null, "TaskWrapperAsyncResult should never wrap a null Task."); + Debug.Assert(task != null, "TaskWrapperAsyncResult should never wrap a null Task."); } // Otherwise, the IAsyncResult should be a Task. else @@ -101,7 +102,7 @@ namespace System.Threading.Tasks if (twar != null) { task = twar.Task as Task<TResult>; - Contract.Assert(twar.Task != null, "TaskWrapperAsyncResult should never wrap a null Task."); + Debug.Assert(twar.Task != null, "TaskWrapperAsyncResult should never wrap a null Task."); } // Otherwise, the IAsyncResult should be a Task<TResult>. else diff --git a/src/mscorlib/src/System/Threading/Tasks/ThreadPoolTaskScheduler.cs b/src/mscorlib/src/System/Threading/Tasks/ThreadPoolTaskScheduler.cs index dd4cbc9a66..5c6ca9bb76 100644 --- a/src/mscorlib/src/System/Threading/Tasks/ThreadPoolTaskScheduler.cs +++ b/src/mscorlib/src/System/Threading/Tasks/ThreadPoolTaskScheduler.cs @@ -13,6 +13,7 @@ using System; using System.Security; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Collections.Generic; using System.Text; @@ -39,7 +40,7 @@ namespace System.Threading.Tasks { Contract.Requires(obj != null, "TaskScheduler.LongRunningThreadWork: obj is null"); Task t = obj as Task; - Contract.Assert(t != null, "TaskScheduler.LongRunningThreadWork: t is null"); + Debug.Assert(t != null, "TaskScheduler.LongRunningThreadWork: t is null"); t.ExecuteEntry(false); } @@ -47,7 +48,6 @@ namespace System.Threading.Tasks /// Schedules a task to the ThreadPool. /// </summary> /// <param name="task">The task to schedule.</param> - [SecurityCritical] protected internal override void QueueTask(Task task) { if ((task.Options & TaskCreationOptions.LongRunning) != 0) @@ -73,7 +73,6 @@ namespace System.Threading.Tasks /// IMPORTANT NOTE: TryExecuteTaskInline will NOT throw task exceptions itself. Any wait code path using this function needs /// to account for exceptions that need to be propagated, and throw themselves accordingly. /// </summary> - [SecurityCritical] protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { // If the task was previously scheduled, and we can't pop it, then return false. @@ -95,14 +94,12 @@ namespace System.Threading.Tasks return rval; } - [SecurityCritical] protected internal override bool TryDequeue(Task task) { // just delegate to TP return ThreadPool.TryPopCustomWorkItem(task); } - [SecurityCritical] protected override IEnumerable<Task> GetScheduledTasks() { return FilterTasksFromWorkItems(ThreadPool.GetQueuedWorkItems()); diff --git a/src/mscorlib/src/System/Threading/Tasks/future.cs b/src/mscorlib/src/System/Threading/Tasks/future.cs index 39e6ca1d45..0c3fec89b7 100644 --- a/src/mscorlib/src/System/Threading/Tasks/future.cs +++ b/src/mscorlib/src/System/Threading/Tasks/future.cs @@ -65,7 +65,6 @@ namespace System.Threading.Tasks /// and may be used from multiple threads concurrently. /// </para> /// </remarks> - [HostProtection(Synchronization = true, ExternalThreading = true)] [DebuggerTypeProxy(typeof(SystemThreadingTasks_FutureDebugView<>))] [DebuggerDisplay("Id = {Id}, Status = {Status}, Method = {DebuggerDisplayMethodDescription}, Result = {DebuggerDisplayResultDescription}")] public class Task<TResult> : Task @@ -447,7 +446,7 @@ namespace System.Threading.Tasks { get { - Delegate d = (Delegate)m_action; + Delegate d = m_action; return d != null ? d.Method.ToString() : "{null}"; } } @@ -457,7 +456,7 @@ namespace System.Threading.Tasks internal bool TrySetResult(TResult result) { if (IsCompleted) return false; - Contract.Assert(m_action == null, "Task<T>.TrySetResult(): non-null m_action"); + Debug.Assert(m_action == null, "Task<T>.TrySetResult(): non-null m_action"); // "Reserve" the completion for this task, while making sure that: (1) No prior reservation // has been made, (2) The result has not already been set, (3) An exception has not previously @@ -497,7 +496,7 @@ namespace System.Threading.Tasks // the task, avoiding expensive completion paths, before the task is actually given to anyone. internal void DangerousSetResult(TResult result) { - Contract.Assert(!IsCompleted, "The promise must not yet be completed."); + Debug.Assert(!IsCompleted, "The promise must not yet be completed."); // If we have a parent, we need to notify it of the completion. Take the slow path to handle that. if (m_contingentProperties?.m_parent != null) @@ -505,7 +504,7 @@ namespace System.Threading.Tasks bool success = TrySetResult(result); // Nobody else has had a chance to complete this Task yet, so we should succeed. - Contract.Assert(success); + Debug.Assert(success); } else { @@ -539,7 +538,7 @@ namespace System.Threading.Tasks { get { - Contract.Assert(!IsWaitNotificationEnabledOrNotRanToCompletion, + Debug.Assert(!IsWaitNotificationEnabledOrNotRanToCompletion, "Should only be used when the task completed successfully and there's no wait notification enabled"); return m_result; } @@ -558,7 +557,7 @@ namespace System.Threading.Tasks if (!IsRanToCompletion) ThrowIfExceptional(includeTaskCanceledExceptions: true); // We shouldn't be here if the result has not been set. - Contract.Assert(IsRanToCompletion, "Task<T>.Result getter: Expected result to have been set."); + Debug.Assert(IsRanToCompletion, "Task<T>.Result getter: Expected result to have been set."); return m_result; } @@ -572,13 +571,13 @@ namespace System.Threading.Tasks // Called from TaskCompletionSource<T>.SetException(IEnumerable<Exception>). internal bool TrySetException(object exceptionObject) { - Contract.Assert(m_action == null, "Task<T>.TrySetException(): non-null m_action"); + Debug.Assert(m_action == null, "Task<T>.TrySetException(): non-null m_action"); // TCS.{Try}SetException() should have checked for this - Contract.Assert(exceptionObject != null, "Expected non-null exceptionObject argument"); + Debug.Assert(exceptionObject != null, "Expected non-null exceptionObject argument"); // Only accept these types. - Contract.Assert( + Debug.Assert( (exceptionObject is Exception) || (exceptionObject is IEnumerable<Exception>) || (exceptionObject is ExceptionDispatchInfo) || (exceptionObject is IEnumerable<ExceptionDispatchInfo>), "Expected exceptionObject to be either Exception, ExceptionDispatchInfo, or IEnumerable<> of one of those"); @@ -620,10 +619,10 @@ namespace System.Threading.Tasks // This method is only valid for promise tasks. internal bool TrySetCanceled(CancellationToken tokenToRecord, object cancellationException) { - Contract.Assert(m_action == null, "Task<T>.TrySetCanceled(): non-null m_action"); + Debug.Assert(m_action == null, "Task<T>.TrySetCanceled(): non-null m_action"); #if DEBUG var ceAsEdi = cancellationException as ExceptionDispatchInfo; - Contract.Assert( + Debug.Assert( cancellationException == null || cancellationException is OperationCanceledException || (ceAsEdi != null && ceAsEdi.SourceException is OperationCanceledException), @@ -669,7 +668,7 @@ namespace System.Threading.Tasks internal override void InnerInvoke() { // Invoke the delegate - Contract.Assert(m_action != null); + Debug.Assert(m_action != null); var func = m_action as Func<TResult>; if (func != null) { @@ -682,7 +681,7 @@ namespace System.Threading.Tasks m_result = funcWithState(m_stateObject); return; } - Contract.Assert(false, "Invalid m_action in Task<TResult>"); + Debug.Assert(false, "Invalid m_action in Task<TResult>"); } #region Await Support |