diff options
Diffstat (limited to 'src/mscorlib/src/System/Threading')
58 files changed, 1044 insertions, 1020 deletions
diff --git a/src/mscorlib/src/System/Threading/AbandonedMutexException.cs b/src/mscorlib/src/System/Threading/AbandonedMutexException.cs index 6b4977fbc5..b39cb208b8 100644 --- a/src/mscorlib/src/System/Threading/AbandonedMutexException.cs +++ b/src/mscorlib/src/System/Threading/AbandonedMutexException.cs @@ -9,77 +9,86 @@ // AbandonedMutexs indicate serious error in user code or machine state. //////////////////////////////////////////////////////////////////////////////// -namespace System.Threading { - - using System; - using System.Runtime.Serialization; - using System.Threading; - using System.Runtime.InteropServices; +using System; +using System.Runtime.Serialization; +using System.Threading; +using System.Runtime.InteropServices; + +namespace System.Threading +{ [Serializable] [ComVisibleAttribute(false)] - public class AbandonedMutexException : SystemException { - + public class AbandonedMutexException : SystemException + { private int m_MutexIndex = -1; private Mutex m_Mutex = null; - public AbandonedMutexException() - : base(Environment.GetResourceString("Threading.AbandonedMutexException")) { + public AbandonedMutexException() + : base(Environment.GetResourceString("Threading.AbandonedMutexException")) + { SetErrorCode(__HResults.COR_E_ABANDONEDMUTEX); } - public AbandonedMutexException(String message) - : base(message) { + public AbandonedMutexException(String message) + : base(message) + { SetErrorCode(__HResults.COR_E_ABANDONEDMUTEX); } - public AbandonedMutexException(String message, Exception inner ) - : base(message, inner) { + public AbandonedMutexException(String message, Exception inner) + : base(message, inner) + { SetErrorCode(__HResults.COR_E_ABANDONEDMUTEX); } - public AbandonedMutexException(int location, WaitHandle handle) - : base(Environment.GetResourceString("Threading.AbandonedMutexException")) { + public AbandonedMutexException(int location, WaitHandle handle) + : base(Environment.GetResourceString("Threading.AbandonedMutexException")) + { SetErrorCode(__HResults.COR_E_ABANDONEDMUTEX); - SetupException(location,handle); + SetupException(location, handle); } - - public AbandonedMutexException(String message,int location, WaitHandle handle) - : base(message) { + + public AbandonedMutexException(String message, int location, WaitHandle handle) + : base(message) + { SetErrorCode(__HResults.COR_E_ABANDONEDMUTEX); - SetupException(location,handle); + SetupException(location, handle); } - public AbandonedMutexException(String message, Exception inner,int location, WaitHandle handle ) - : base(message, inner) { + public AbandonedMutexException(String message, Exception inner, int location, WaitHandle handle) + : base(message, inner) + { SetErrorCode(__HResults.COR_E_ABANDONEDMUTEX); - SetupException(location,handle); + SetupException(location, handle); } private void SetupException(int location, WaitHandle handle) { m_MutexIndex = location; - if(handle != null) + if (handle != null) m_Mutex = handle as Mutex; } - protected AbandonedMutexException(SerializationInfo info, StreamingContext context) : base(info, context) { + protected AbandonedMutexException(SerializationInfo info, StreamingContext context) : base(info, context) + { } public Mutex Mutex { - get { + get + { return m_Mutex; } } public int MutexIndex { - get{ + get + { return m_MutexIndex; } } - } } - + diff --git a/src/mscorlib/src/System/Threading/ApartmentState.cs b/src/mscorlib/src/System/Threading/ApartmentState.cs index 1edf0af98a..445d70f1c6 100644 --- a/src/mscorlib/src/System/Threading/ApartmentState.cs +++ b/src/mscorlib/src/System/Threading/ApartmentState.cs @@ -12,11 +12,11 @@ ** =============================================================================*/ -namespace System.Threading { - +namespace System.Threading +{ [Serializable] public enum ApartmentState - { + { /*========================================================================= ** Constants for thread apartment states. =========================================================================*/ diff --git a/src/mscorlib/src/System/Threading/AsyncLocal.cs b/src/mscorlib/src/System/Threading/AsyncLocal.cs index 8c4319bd2c..b1d90b3983 100644 --- a/src/mscorlib/src/System/Threading/AsyncLocal.cs +++ b/src/mscorlib/src/System/Threading/AsyncLocal.cs @@ -46,7 +46,7 @@ namespace System.Threading // // Constructs an AsyncLocal<T> that does not receive change notifications. // - public AsyncLocal() + public AsyncLocal() { } @@ -54,21 +54,21 @@ namespace System.Threading // Constructs an AsyncLocal<T> with a delegate that is called whenever the current value changes // on any thread. // - public AsyncLocal(Action<AsyncLocalValueChangedArgs<T>> valueChangedHandler) + public AsyncLocal(Action<AsyncLocalValueChangedArgs<T>> valueChangedHandler) { m_valueChangedHandler = valueChangedHandler; } public T Value { - get - { + get + { object obj = ExecutionContext.GetLocalValue(this); return (obj == null) ? default(T) : (T)obj; } - set + set { - ExecutionContext.SetLocalValue(this, value, m_valueChangedHandler != null); + ExecutionContext.SetLocalValue(this, value, m_valueChangedHandler != null); } } @@ -93,7 +93,7 @@ namespace System.Threading { public T PreviousValue { get; private set; } public T CurrentValue { get; private set; } - + // // If the value changed because we changed to a different ExecutionContext, this is true. If it changed // because someone set the Value property, this is false. @@ -114,7 +114,7 @@ namespace System.Threading // Implementations are specialized based on the number of elements in the immutable // map in order to minimize memory consumption and look-up times. // - interface IAsyncLocalValueMap + internal interface IAsyncLocalValueMap { bool TryGetValue(IAsyncLocal key, out object value); IAsyncLocalValueMap Set(IAsyncLocal key, object value); diff --git a/src/mscorlib/src/System/Threading/AutoResetEvent.cs b/src/mscorlib/src/System/Threading/AutoResetEvent.cs index fc6b2301ca..41a012cf58 100644 --- a/src/mscorlib/src/System/Threading/AutoResetEvent.cs +++ b/src/mscorlib/src/System/Threading/AutoResetEvent.cs @@ -11,14 +11,15 @@ ** ** =============================================================================*/ -namespace System.Threading { - - using System; - using System.Runtime.InteropServices; +using System; +using System.Runtime.InteropServices; + +namespace System.Threading +{ public sealed class AutoResetEvent : EventWaitHandle { - public AutoResetEvent(bool initialState) : base(initialState,EventResetMode.AutoReset){ } + public AutoResetEvent(bool initialState) : base(initialState, EventResetMode.AutoReset) { } } } - + diff --git a/src/mscorlib/src/System/Threading/CancellationToken.cs b/src/mscorlib/src/System/Threading/CancellationToken.cs index b68ba4c046..4d8212044c 100644 --- a/src/mscorlib/src/System/Threading/CancellationToken.cs +++ b/src/mscorlib/src/System/Threading/CancellationToken.cs @@ -78,14 +78,14 @@ namespace System.Threading /// particularly in situations where related objects are being canceled concurrently. /// </para> /// </remarks> - public bool IsCancellationRequested + public bool IsCancellationRequested { get { return m_source != null && m_source.IsCancellationRequested; } } - + /// <summary> /// Gets whether this token is capable of being in the canceled state. /// </summary> @@ -153,12 +153,12 @@ namespace System.Threading public CancellationToken(bool canceled) : this() { - if(canceled) + if (canceled) m_source = CancellationTokenSource.InternalGetStaticSource(canceled); } /* Methods */ - + private readonly static Action<Object> s_ActionToActionObjShunt = new Action<Object>(ActionToActionObjShunt); private static void ActionToActionObjShunt(object obj) @@ -190,7 +190,7 @@ namespace System.Threading { if (callback == null) throw new ArgumentNullException(nameof(callback)); - + return Register( s_ActionToActionObjShunt, callback, @@ -225,7 +225,7 @@ namespace System.Threading { if (callback == null) throw new ArgumentNullException(nameof(callback)); - + return Register( s_ActionToActionObjShunt, callback, @@ -301,7 +301,7 @@ namespace System.Threading true // useExecutionContext=true ); } - + // helper for internal registration needs that don't require an EC capture (e.g. creating linked token sources, or registering unstarted TPL tasks) // has a handy signature, and skips capturing execution context. internal CancellationTokenRegistration InternalRegisterWithoutEC(Action<object> callback, Object state) @@ -366,14 +366,14 @@ namespace System.Threading { return other.m_source == CancellationTokenSource.InternalGetStaticSource(false); } - + if (other.m_source == null) { return m_source == CancellationTokenSource.InternalGetStaticSource(false); } // general case, we check if the sources are identical - + return m_source == other.m_source; } @@ -392,7 +392,7 @@ namespace System.Threading { if (other is CancellationToken) { - return Equals((CancellationToken) other); + return Equals((CancellationToken)other); } return false; @@ -410,9 +410,9 @@ namespace System.Threading return CancellationTokenSource.InternalGetStaticSource(false).GetHashCode(); } - return m_source.GetHashCode(); + return m_source.GetHashCode(); } - + /// <summary> /// Determines whether two <see cref="T:System.Threading.CancellationToken">CancellationToken</see> instances are equal. /// </summary> @@ -455,7 +455,7 @@ namespace System.Threading /// cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> has been disposed.</exception> public void ThrowIfCancellationRequested() { - if (IsCancellationRequested) + if (IsCancellationRequested) ThrowOperationCanceledException(); } @@ -479,7 +479,7 @@ namespace System.Threading // ----------------------------------- // Private helpers - + private void InitializeDefaultSource() { // Lazy is slower, and although multiple threads may try and set m_source repeatedly, the race condition is benign. diff --git a/src/mscorlib/src/System/Threading/CancellationTokenRegistration.cs b/src/mscorlib/src/System/Threading/CancellationTokenRegistration.cs index 89e98fa3c8..be760fab3f 100644 --- a/src/mscorlib/src/System/Threading/CancellationTokenRegistration.cs +++ b/src/mscorlib/src/System/Threading/CancellationTokenRegistration.cs @@ -62,7 +62,7 @@ namespace System.Threading // Remove the entry from the array. // This call includes a full memory fence which prevents potential reorderings of the reads below bool deregisterOccurred = TryDeregister(); - + // We guarantee that we will not return if the callback is being executed (assuming we are not currently called by the callback itself) // We achieve this by the following rules: // 1. if we are called in the context of an executing callback, no need to wait (determined by tracking callback-executor threadID) @@ -124,7 +124,7 @@ namespace System.Threading /// </returns> public override bool Equals(object obj) { - return ((obj is CancellationTokenRegistration) && Equals((CancellationTokenRegistration) obj)); + return ((obj is CancellationTokenRegistration) && Equals((CancellationTokenRegistration)obj)); } /// <summary> @@ -152,7 +152,7 @@ namespace System.Threading { if (m_registrationInfo.Source != null) return m_registrationInfo.Source.GetHashCode() ^ m_registrationInfo.Index.GetHashCode(); - + return m_registrationInfo.Index.GetHashCode(); } } diff --git a/src/mscorlib/src/System/Threading/CancellationTokenSource.cs b/src/mscorlib/src/System/Threading/CancellationTokenSource.cs index 1e70d6f30f..eef3a15644 100644 --- a/src/mscorlib/src/System/Threading/CancellationTokenSource.cs +++ b/src/mscorlib/src/System/Threading/CancellationTokenSource.cs @@ -45,18 +45,18 @@ namespace System.Threading // the actual callback lists are only created on demand. // Storing a registered callback costs around >60bytes, hence some overhead for the lists array is OK // At most 24 lists seems reasonable, and caps the cost of the listsArray to 96bytes(32-bit,24-way) or 192bytes(64-bit,24-way). - private static readonly int s_nLists = (PlatformHelper.ProcessorCount > 24) ? 24 : PlatformHelper.ProcessorCount; + private static readonly int s_nLists = (PlatformHelper.ProcessorCount > 24) ? 24 : PlatformHelper.ProcessorCount; private volatile ManualResetEvent m_kernelEvent; //lazily initialized if required. private volatile SparselyPopulatedArray<CancellationCallbackInfo>[] m_registeredCallbacksLists; - + // legal values for m_state private const int CANNOT_BE_CANCELED = 0; private const int NOT_CANCELED = 1; private const int NOTIFYING = 2; private const int NOTIFYINGCOMPLETE = 3; - + //m_state uses the pattern "volatile int32 reads, with cmpxch writes" which is safe for updates and cannot suffer torn reads. private volatile int m_state; @@ -68,13 +68,13 @@ namespace System.Threading private volatile int m_threadIDExecutingCallbacks = -1; private bool m_disposed; - + // we track the running callback to assist ctr.Dispose() to wait for the target callback to complete. private volatile CancellationCallbackInfo m_executingCallback; // provided for CancelAfter and timer-related constructors private volatile Timer m_timer; - + // ---------------------- // ** public properties @@ -168,11 +168,11 @@ namespace System.Threading // fast path if already allocated. if (m_kernelEvent != null) return m_kernelEvent; - + // lazy-init the mre. ManualResetEvent mre = new ManualResetEvent(false); if (Interlocked.CompareExchange(ref m_kernelEvent, mre, null) != null) - { + { ((IDisposable)mre).Dispose(); } @@ -211,9 +211,9 @@ namespace System.Threading return 0; int count = 0; - foreach(SparselyPopulatedArray<CancellationCallbackInfo> sparseArray in callbackLists) + foreach (SparselyPopulatedArray<CancellationCallbackInfo> sparseArray in callbackLists) { - if(sparseArray != null) + if (sparseArray != null) { SparselyPopulatedArrayFragment<CancellationCallbackInfo> currCallbacks = sparseArray.Head; while (currCallbacks != null) @@ -379,7 +379,7 @@ namespace System.Threading public void Cancel(bool throwOnFirstException) { ThrowIfDisposed(); - NotifyCancellation(throwOnFirstException); + NotifyCancellation(throwOnFirstException); } /// <summary> @@ -476,7 +476,7 @@ namespace System.Threading } } - + // It is possible that m_timer has already been disposed, so we must do // the following in a try/catch block. try @@ -490,7 +490,6 @@ namespace System.Threading // would not be a good way to deal with the observe/dispose // race condition. } - } private static readonly TimerCallback s_timerCallback = new TimerCallback(TimerCallbackLogic); @@ -716,7 +715,7 @@ namespace System.Threading // Record the threadID being used for running the callbacks. ThreadIDExecutingCallbacks = Thread.CurrentThread.ManagedThreadId; - + // Set the event if it's been lazily initialized and hasn't yet been disposed of. Dispose may // be running concurrently, in which case either it'll have set m_kernelEvent back to null and // we won't see it here, or it'll see that we've transitioned to NOTIFYING and will skip disposing it, @@ -755,7 +754,7 @@ namespace System.Threading Interlocked.Exchange(ref m_state, NOTIFYINGCOMPLETE); return; } - + try { for (int index = 0; index < callbackLists.Length; index++) @@ -799,13 +798,13 @@ namespace System.Threading CancellationCallbackCoreWork(args); } } - catch(Exception ex) + catch (Exception ex) { if (throwOnFirstException) throw; - + // Otherwise, log it and proceed. - if(exceptionList == null) + if (exceptionList == null) exceptionList = new List<Exception>(); exceptionList.Add(ex); } @@ -1004,7 +1003,7 @@ namespace System.Threading { internal SparselyPopulatedArrayFragment<CancellationCallbackInfo> m_currArrayFragment; internal int m_currArrayIndex; - + public CancellationCallbackCoreWorkArguments(SparselyPopulatedArrayFragment<CancellationCallbackInfo> currArrayFragment, int currArrayIndex) { m_currArrayFragment = currArrayFragment; @@ -1040,7 +1039,6 @@ namespace System.Threading { TargetSyncContext = targetSyncContext; } - } internal CancellationCallbackInfo( @@ -1066,7 +1064,7 @@ namespace System.Threading // Lazily initialize the callback delegate; benign race condition var callback = s_executionContextCallback; if (callback == null) s_executionContextCallback = callback = new ContextCallback(ExecutionContextCallback); - + ExecutionContext.Run( TargetExecutionContext, callback, @@ -1176,7 +1174,7 @@ namespace System.Threading // If the slot is null, try to CAS our element into it. int tryIndex = (start + i) % c; Debug.Assert(tryIndex >= 0 && tryIndex < curr.m_elements.Length, "tryIndex is outside of bounds"); - + if (curr.m_elements[tryIndex] == null && Interlocked.CompareExchange(ref curr.m_elements[tryIndex], element, null) == null) { // We adjust the free count by --. Note: if this drops to 0, we will skip @@ -1282,7 +1280,7 @@ namespace System.Threading internal T SafeAtomicRemove(int index, T expectedElement) { T prevailingValue = Interlocked.CompareExchange(ref m_elements[index], null, expectedElement); - if (prevailingValue != null) + if (prevailingValue != null) ++m_freeCount; return prevailingValue; } diff --git a/src/mscorlib/src/System/Threading/CountdownEvent.cs b/src/mscorlib/src/System/Threading/CountdownEvent.cs index af055e347e..8a36a84dc3 100644 --- a/src/mscorlib/src/System/Threading/CountdownEvent.cs +++ b/src/mscorlib/src/System/Threading/CountdownEvent.cs @@ -18,7 +18,6 @@ using System.Diagnostics.Contracts; namespace System.Threading { - /// <summary> /// Represents a synchronization primitive that is signaled when its count reaches zero. /// </summary> @@ -80,7 +79,7 @@ namespace System.Threading /// </value> public int CurrentCount { - get + get { int observedCount = m_currentCount; return observedCount < 0 ? 0 : observedCount; diff --git a/src/mscorlib/src/System/Threading/EventResetMode.cs b/src/mscorlib/src/System/Threading/EventResetMode.cs index edafab9bb5..89bf7a769e 100644 --- a/src/mscorlib/src/System/Threading/EventResetMode.cs +++ b/src/mscorlib/src/System/Threading/EventResetMode.cs @@ -14,9 +14,10 @@ =============================================================================*/ +using System.Runtime.InteropServices; + namespace System.Threading { - using System.Runtime.InteropServices; [ComVisibleAttribute(false)] public enum EventResetMode { diff --git a/src/mscorlib/src/System/Threading/EventWaitHandle.cs b/src/mscorlib/src/System/Threading/EventWaitHandle.cs index 0268948a5c..034c4b0ee6 100644 --- a/src/mscorlib/src/System/Threading/EventWaitHandle.cs +++ b/src/mscorlib/src/System/Threading/EventWaitHandle.cs @@ -39,11 +39,11 @@ namespace System.Threading [ComVisibleAttribute(true)] public class EventWaitHandle : WaitHandle { - public EventWaitHandle(bool initialState, EventResetMode mode) : this(initialState,mode,null) { } + public EventWaitHandle(bool initialState, EventResetMode mode) : this(initialState, mode, null) { } public EventWaitHandle(bool initialState, EventResetMode mode, string name) { - if(name != null) + if (name != null) { #if PLATFORM_UNIX throw new PlatformNotSupportedException(Environment.GetResourceString("PlatformNotSupported_NamedSynchronizationPrimitives")); @@ -55,9 +55,9 @@ namespace System.Threading #endif } Contract.EndContractBlock(); - + SafeWaitHandle _handle = null; - switch(mode) + switch (mode) { case EventResetMode.ManualReset: _handle = Win32Native.CreateEvent(null, true, initialState, name); @@ -67,16 +67,16 @@ namespace System.Threading break; default: - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag",name)); + throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag", name)); }; - + if (_handle.IsInvalid) { int errorCode = Marshal.GetLastWin32Error(); - + _handle.SetHandleAsInvalid(); - if(null != name && 0 != name.Length && Win32Native.ERROR_INVALID_HANDLE == errorCode) - throw new WaitHandleCannotBeOpenedException(Environment.GetResourceString("Threading.WaitHandleCannotBeOpenedException_InvalidHandle",name)); + if (null != name && 0 != name.Length && Win32Native.ERROR_INVALID_HANDLE == errorCode) + throw new WaitHandleCannotBeOpenedException(Environment.GetResourceString("Threading.WaitHandleCannotBeOpenedException_InvalidHandle", name)); __Error.WinIOError(errorCode, name); } @@ -90,7 +90,7 @@ namespace System.Threading internal unsafe EventWaitHandle(bool initialState, EventResetMode mode, string name, out bool createdNew, EventWaitHandleSecurity eventSecurity) { - if(name != null) + if (name != null) { #if PLATFORM_UNIX throw new PlatformNotSupportedException(Environment.GetResourceString("PlatformNotSupported_NamedSynchronizationPrimitives")); @@ -106,7 +106,7 @@ namespace System.Threading SafeWaitHandle _handle = null; Boolean isManualReset; - switch(mode) + switch (mode) { case EventResetMode.ManualReset: isManualReset = true; @@ -116,7 +116,7 @@ namespace System.Threading break; default: - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag",name)); + throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag", name)); }; _handle = Win32Native.CreateEvent(secAttrs, isManualReset, initialState, name); @@ -124,10 +124,9 @@ namespace System.Threading if (_handle.IsInvalid) { - _handle.SetHandleAsInvalid(); - if(null != name && 0 != name.Length && Win32Native.ERROR_INVALID_HANDLE == errorCode) - throw new WaitHandleCannotBeOpenedException(Environment.GetResourceString("Threading.WaitHandleCannotBeOpenedException_InvalidHandle",name)); + if (null != name && 0 != name.Length && Win32Native.ERROR_INVALID_HANDLE == errorCode) + throw new WaitHandleCannotBeOpenedException(Environment.GetResourceString("Threading.WaitHandleCannotBeOpenedException_InvalidHandle", name)); __Error.WinIOError(errorCode, name); } @@ -180,16 +179,16 @@ namespace System.Threading throw new ArgumentNullException(nameof(name), Environment.GetResourceString("ArgumentNull_WithParamName")); } - if(name.Length == 0) + if (name.Length == 0) { throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(name)); } - if(null != name && System.IO.Path.MaxPath < name.Length) + if (null != name && System.IO.Path.MaxPath < name.Length) { throw new ArgumentException(Environment.GetResourceString("Argument_WaitHandleNameTooLong", Path.MaxPath), nameof(name)); } - + Contract.EndContractBlock(); result = null; @@ -200,14 +199,14 @@ namespace System.Threading { int errorCode = Marshal.GetLastWin32Error(); - if(Win32Native.ERROR_FILE_NOT_FOUND == errorCode || Win32Native.ERROR_INVALID_NAME == errorCode) + if (Win32Native.ERROR_FILE_NOT_FOUND == errorCode || Win32Native.ERROR_INVALID_NAME == errorCode) return OpenExistingResult.NameNotFound; if (Win32Native.ERROR_PATH_NOT_FOUND == errorCode) return OpenExistingResult.PathNotFound; - if(null != name && 0 != name.Length && Win32Native.ERROR_INVALID_HANDLE == errorCode) + if (null != name && 0 != name.Length && Win32Native.ERROR_INVALID_HANDLE == errorCode) return OpenExistingResult.NameInvalid; //this is for passed through Win32Native Errors - __Error.WinIOError(errorCode,""); + __Error.WinIOError(errorCode, ""); } result = new EventWaitHandle(myHandle); return OpenExistingResult.Success; diff --git a/src/mscorlib/src/System/Threading/ExecutionContext.cs b/src/mscorlib/src/System/Threading/ExecutionContext.cs index 47a55a3bb9..1e9e9b4ef1 100644 --- a/src/mscorlib/src/System/Threading/ExecutionContext.cs +++ b/src/mscorlib/src/System/Threading/ExecutionContext.cs @@ -9,23 +9,24 @@ ** ** ===========================================================*/ -namespace System.Threading -{ - using System; - using System.Security; - using System.Runtime.Remoting; - using System.Collections; - using System.Collections.Generic; - using System.Reflection; - using System.Runtime.ExceptionServices; - using System.Runtime.Serialization; - using System.Runtime.InteropServices; - using System.Runtime.CompilerServices; - using System.Runtime.ConstrainedExecution; - using System.Diagnostics; - using System.Diagnostics.Contracts; - using System.Diagnostics.CodeAnalysis; +using System; +using System.Security; +using System.Runtime.Remoting; +using System.Collections; +using System.Collections.Generic; +using System.Reflection; +using System.Runtime.ExceptionServices; +using System.Runtime.Serialization; +using System.Runtime.InteropServices; +using System.Runtime.CompilerServices; +using System.Runtime.ConstrainedExecution; +using System.Diagnostics; +using System.Diagnostics.Contracts; +using System.Diagnostics.CodeAnalysis; + +namespace System.Threading +{ public delegate void ContextCallback(Object state); internal struct ExecutionContextSwitcher @@ -42,7 +43,7 @@ namespace System.Threading { currentThread.SynchronizationContext = m_sc; } - + if (currentThread.ExecutionContext != m_ec) { ExecutionContext.Restore(currentThread, m_ec); @@ -178,11 +179,11 @@ namespace System.Threading ExecutionContext previous = currentThread.ExecutionContext ?? Default; currentThread.ExecutionContext = executionContext; - + // New EC could be null if that's what ECS.Undo saved off. // For the purposes of dealing with context change, treat this as the default EC executionContext = executionContext ?? Default; - + if (previous != executionContext) { OnContextChanged(previous, executionContext); @@ -192,8 +193,8 @@ namespace System.Threading static internal void EstablishCopyOnWriteScope(Thread currentThread, ref ExecutionContextSwitcher ecsw) { Debug.Assert(currentThread == Thread.CurrentThread); - - ecsw.m_ec = currentThread.ExecutionContext; + + ecsw.m_ec = currentThread.ExecutionContext; ecsw.m_sc = currentThread.SynchronizationContext; } @@ -203,7 +204,7 @@ namespace System.Threading Debug.Assert(previous != null); Debug.Assert(current != null); Debug.Assert(previous != current); - + foreach (IAsyncLocal local in previous.m_localChangeNotifications) { object previousValue; @@ -237,10 +238,10 @@ namespace System.Threading catch (Exception ex) { Environment.FailFast( - Environment.GetResourceString("ExecutionContext_ExceptionInAsyncLocalNotification"), + Environment.GetResourceString("ExecutionContext_ExceptionInAsyncLocalNotification"), ex); } - } + } } internal static object GetLocalValue(IAsyncLocal local) diff --git a/src/mscorlib/src/System/Threading/Interlocked.cs b/src/mscorlib/src/System/Threading/Interlocked.cs index 131d51a65b..578201e5a3 100644 --- a/src/mscorlib/src/System/Threading/Interlocked.cs +++ b/src/mscorlib/src/System/Threading/Interlocked.cs @@ -3,21 +3,22 @@ // See the LICENSE file in the project root for more information. // + +using System; +using System.Runtime.CompilerServices; +using System.Runtime.ConstrainedExecution; +using System.Runtime.Versioning; +using System.Runtime; + namespace System.Threading { - using System; - using System.Runtime.CompilerServices; - using System.Runtime.ConstrainedExecution; - using System.Runtime.Versioning; - using System.Runtime; - // After much discussion, we decided the Interlocked class doesn't need // any HPA's for synchronization or external threading. They hurt C#'s // codegen for the yield keyword, and arguably they didn't protect much. // Instead, they penalized people (and compilers) for writing threadsafe // code. public static class Interlocked - { + { /****************************** * Increment * Implemented: int @@ -102,16 +103,16 @@ namespace System.Threading *****************************/ [MethodImplAttribute(MethodImplOptions.InternalCall)] - public static extern int CompareExchange(ref int location1, int value, int comparand); + public static extern int CompareExchange(ref int location1, int value, int comparand); [MethodImplAttribute(MethodImplOptions.InternalCall)] - public static extern long CompareExchange(ref long location1, long value, long comparand); + public static extern long CompareExchange(ref long location1, long value, long comparand); [MethodImplAttribute(MethodImplOptions.InternalCall)] - public static extern float CompareExchange(ref float location1, float value, float comparand); + public static extern float CompareExchange(ref float location1, float value, float comparand); [MethodImplAttribute(MethodImplOptions.InternalCall)] - public static extern double CompareExchange(ref double location1, double value, double comparand); + public static extern double CompareExchange(ref double location1, double value, double comparand); [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern Object CompareExchange(ref Object location1, Object value, Object comparand); @@ -142,7 +143,7 @@ namespace System.Threading * See getILIntrinsicImplementationForInterlocked() in VM\JitInterface.cpp * for details. *****************************************************************/ - + public static T CompareExchange<T>(ref T location1, T value, T comparand) where T : class { // _CompareExchange() passes back the value read from location1 via local named 'value' @@ -169,22 +170,22 @@ namespace System.Threading [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern long ExchangeAdd(ref long location1, long value); - public static int Add(ref int location1, int value) + public static int Add(ref int location1, int value) { return ExchangeAdd(ref location1, value) + value; } - public static long Add(ref long location1, long value) + public static long Add(ref long location1, long value) { return ExchangeAdd(ref location1, value) + value; } - + /****************************** * Read *****************************/ public static long Read(ref long location) { - return Interlocked.CompareExchange(ref location,0,0); + return Interlocked.CompareExchange(ref location, 0, 0); } diff --git a/src/mscorlib/src/System/Threading/LazyInitializer.cs b/src/mscorlib/src/System/Threading/LazyInitializer.cs index af32673d03..82fb2579bb 100644 --- a/src/mscorlib/src/System/Threading/LazyInitializer.cs +++ b/src/mscorlib/src/System/Threading/LazyInitializer.cs @@ -13,9 +13,9 @@ using System.Diagnostics; using System.Diagnostics.Contracts; + namespace System.Threading { - /// <summary> /// Specifies how a <see cref="T:System.Threading.Lazy{T}"/> instance should synchronize access among multiple threads. /// </summary> @@ -241,11 +241,10 @@ namespace System.Threading return target; } - } // Caches the activation selector function to avoid delegate allocations. - static class LazyHelpers<T> + internal static class LazyHelpers<T> { internal static Func<T> s_activatorFactorySelector = new Func<T>(ActivatorFactorySelector); diff --git a/src/mscorlib/src/System/Threading/LockRecursionException.cs b/src/mscorlib/src/System/Threading/LockRecursionException.cs index 40f04b00b4..5624282a40 100644 --- a/src/mscorlib/src/System/Threading/LockRecursionException.cs +++ b/src/mscorlib/src/System/Threading/LockRecursionException.cs @@ -12,12 +12,12 @@ // support it in its current state. ============================================================*/ +using System; +using System.Runtime.Serialization; +using System.Runtime.CompilerServices; + namespace System.Threading { - using System; - using System.Runtime.Serialization; - using System.Runtime.CompilerServices; - [Serializable] public class LockRecursionException : System.Exception { @@ -26,5 +26,4 @@ namespace System.Threading protected LockRecursionException(SerializationInfo info, StreamingContext context) : base(info, context) { } public LockRecursionException(string message, Exception innerException) : base(message, innerException) { } } - } diff --git a/src/mscorlib/src/System/Threading/ManualResetEvent.cs b/src/mscorlib/src/System/Threading/ManualResetEvent.cs index a8e012fb43..bb875c4f49 100644 --- a/src/mscorlib/src/System/Threading/ManualResetEvent.cs +++ b/src/mscorlib/src/System/Threading/ManualResetEvent.cs @@ -11,14 +11,15 @@ ** ** =============================================================================*/ -namespace System.Threading { - - using System; - using System.Runtime.InteropServices; +using System; +using System.Runtime.InteropServices; + +namespace System.Threading +{ public sealed class ManualResetEvent : EventWaitHandle - { - public ManualResetEvent(bool initialState) : base(initialState,EventResetMode.ManualReset){} + { + public ManualResetEvent(bool initialState) : base(initialState, EventResetMode.ManualReset) { } } } - + diff --git a/src/mscorlib/src/System/Threading/ManualResetEventSlim.cs b/src/mscorlib/src/System/Threading/ManualResetEventSlim.cs index 2d57b4102b..c0bdbcece2 100644 --- a/src/mscorlib/src/System/Threading/ManualResetEventSlim.cs +++ b/src/mscorlib/src/System/Threading/ManualResetEventSlim.cs @@ -20,7 +20,6 @@ using System.Diagnostics.Contracts; namespace System.Threading { - // ManualResetEventSlim wraps a manual-reset event internally with a little bit of // spinning. When an event will be set imminently, it is often advantageous to avoid // a 4k+ cycle context switch in favor of briefly spinning. Therefore we layer on to @@ -98,7 +97,6 @@ namespace System.Threading /// </remarks> public WaitHandle WaitHandle { - get { ThrowIfDisposed(); @@ -169,7 +167,6 @@ namespace System.Threading UpdateStateAtomically(value << NumWaitersState_ShiftCount, NumWaitersState_BitMask); } - } //----------------------------------------------------------------------------------- @@ -184,7 +181,6 @@ namespace System.Threading public ManualResetEventSlim() : this(false) { - } /// <summary> @@ -236,14 +232,13 @@ namespace System.Threading /// <param name="spinCount">The spin count that decides when the event will block.</param> private void Initialize(bool initialState, int spinCount) { - this.m_combinedState = initialState ? (1 << SignalledState_ShiftCount) : 0; + m_combinedState = initialState ? (1 << SignalledState_ShiftCount) : 0; //the spinCount argument has been validated by the ctors. //but we now sanity check our predefined constants. Debug.Assert(DEFAULT_SPIN_SP >= 0, "Internal error - DEFAULT_SPIN_SP is outside the legal range."); Debug.Assert(DEFAULT_SPIN_SP <= SpinCountState_MaxValue, "Internal error - DEFAULT_SPIN_SP is outside the legal range."); SpinCount = PlatformHelper.IsSingleProcessor ? DEFAULT_SPIN_SP : spinCount; - } /// <summary> @@ -283,7 +278,6 @@ namespace System.Threading } else { - // Now that the event is published, verify that the state hasn't changed since // we snapped the preInitializeState. Another thread could have done that // between our initial observation above and here. The barrier incurred from @@ -337,7 +331,6 @@ namespace System.Threading Debug.Assert(m_lock != null); //if waiters>0, then m_lock has already been created. lock (m_lock) { - Monitor.PulseAll(m_lock); } } @@ -665,7 +658,6 @@ namespace System.Threading // Now just loop back around, and the right thing will happen. Either: // 1. We had a spurious wake-up due to some other wait being canceled via a different cancellationToken (rewait) // or 2. the wait was successful. (the loop will break) - } } } diff --git a/src/mscorlib/src/System/Threading/Monitor.cs b/src/mscorlib/src/System/Threading/Monitor.cs index fdbc384243..8cebe647bb 100644 --- a/src/mscorlib/src/System/Threading/Monitor.cs +++ b/src/mscorlib/src/System/Threading/Monitor.cs @@ -14,19 +14,20 @@ =============================================================================*/ -namespace System.Threading { - - using System; - using System.Runtime; - using System.Runtime.Remoting; - using System.Threading; - using System.Runtime.CompilerServices; - using System.Runtime.ConstrainedExecution; - using System.Runtime.Versioning; - using System.Diagnostics; - using System.Diagnostics.Contracts; - - public static class Monitor + +using System; +using System.Runtime; +using System.Runtime.Remoting; +using System.Threading; +using System.Runtime.CompilerServices; +using System.Runtime.ConstrainedExecution; +using System.Runtime.Versioning; +using System.Diagnostics; +using System.Diagnostics.Contracts; + +namespace System.Threading +{ + public static class Monitor { /*========================================================================= ** Obtain the monitor lock of obj. Will block if another thread holds the lock @@ -75,7 +76,7 @@ namespace System.Threading { =========================================================================*/ [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern void Exit(Object obj); - + /*========================================================================= ** Similar to Enter, but will never block. That is, if the current thread can ** acquire the monitor lock without blocking, it will do so and TRUE will @@ -99,7 +100,7 @@ namespace System.Threading { ReliableEnterTimeout(obj, 0, ref lockTaken); } - + /*========================================================================= ** Version of TryEnter that will block, but only up to a timeout period ** expressed in milliseconds. If timeout == Timeout.Infinite the method diff --git a/src/mscorlib/src/System/Threading/Mutex.cs b/src/mscorlib/src/System/Threading/Mutex.cs index dcb821307a..cac423f6a8 100644 --- a/src/mscorlib/src/System/Threading/Mutex.cs +++ b/src/mscorlib/src/System/Threading/Mutex.cs @@ -11,8 +11,9 @@ ** ** =============================================================================*/ -namespace System.Threading -{ + +namespace System.Threading +{ using System; using System.Threading; using System.Runtime.CompilerServices; @@ -28,7 +29,7 @@ namespace System.Threading public sealed class Mutex : WaitHandle { - static bool dummyBool; + private static bool dummyBool; internal class MutexSecurity { @@ -67,20 +68,20 @@ namespace System.Threading RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup( tryCode, cleanupCode, - cleanupInfo); + cleanupInfo); createdNew = tryCodeHelper.m_newMutex; } - internal class MutexTryCodeHelper + internal class MutexTryCodeHelper { - bool m_initiallyOwned; - MutexCleanupInfo m_cleanupInfo; + private bool m_initiallyOwned; + private MutexCleanupInfo m_cleanupInfo; internal bool m_newMutex; - String m_name; - Win32Native.SECURITY_ATTRIBUTES m_secAttrs; - Mutex m_mutex; + private String m_name; + private Win32Native.SECURITY_ATTRIBUTES m_secAttrs; + private Mutex m_mutex; - internal MutexTryCodeHelper(bool initiallyOwned,MutexCleanupInfo cleanupInfo, String name, Win32Native.SECURITY_ATTRIBUTES secAttrs, Mutex mutex) + internal MutexTryCodeHelper(bool initiallyOwned, MutexCleanupInfo cleanupInfo, String name, Win32Native.SECURITY_ATTRIBUTES secAttrs, Mutex mutex) { Debug.Assert(name == null || name.Length != 0); @@ -92,16 +93,16 @@ namespace System.Threading } internal void MutexTryCode(object userData) - { + { SafeWaitHandle mutexHandle = null; // try block RuntimeHelpers.PrepareConstrainedRegions(); - try + try { } - finally + finally { - if (m_initiallyOwned) + if (m_initiallyOwned) { m_cleanupInfo.inCriticalRegion = true; } @@ -109,15 +110,15 @@ namespace System.Threading int errorCode = 0; RuntimeHelpers.PrepareConstrainedRegions(); - try + try { } - finally + finally { errorCode = CreateMutexHandle(m_initiallyOwned, m_name, m_secAttrs, out mutexHandle); - } + } - if (mutexHandle.IsInvalid) + if (mutexHandle.IsInvalid) { mutexHandle.SetHandleAsInvalid(); if (m_name != null) @@ -140,19 +141,21 @@ namespace System.Threading m_mutex.SetHandleInternal(mutexHandle); m_mutex.hasThreadAffinity = true; - } } private void MutexCleanupCode(Object userData, bool exceptionThrown) { - MutexCleanupInfo cleanupInfo = (MutexCleanupInfo) userData; - + MutexCleanupInfo cleanupInfo = (MutexCleanupInfo)userData; + // If hasThreadAffinity isn't true, we've thrown an exception in the above try, and we must free the mutex // on this OS thread before ending our thread affninity. - if(!hasThreadAffinity) { - if (cleanupInfo.mutexHandle != null && !cleanupInfo.mutexHandle.IsInvalid) { - if( cleanupInfo.inCriticalRegion) { + if (!hasThreadAffinity) + { + if (cleanupInfo.mutexHandle != null && !cleanupInfo.mutexHandle.IsInvalid) + { + if (cleanupInfo.inCriticalRegion) + { Win32Native.ReleaseMutex(cleanupInfo.mutexHandle); } cleanupInfo.mutexHandle.Dispose(); @@ -171,7 +174,8 @@ namespace System.Threading } } - public Mutex(bool initiallyOwned, String name) : this(initiallyOwned, name, out dummyBool) { + public Mutex(bool initiallyOwned, String name) : this(initiallyOwned, name, out dummyBool) + { } public Mutex(bool initiallyOwned) : this(initiallyOwned, null, out dummyBool) @@ -181,7 +185,7 @@ namespace System.Threading public Mutex() : this(false, null, out dummyBool) { } - + private Mutex(SafeWaitHandle handle) { SetHandleInternal(handle); @@ -190,7 +194,7 @@ namespace System.Threading public static Mutex OpenExisting(string name) { - return OpenExisting(name, (MutexRights) 0); + return OpenExisting(name, (MutexRights)0); } internal enum MutexRights @@ -229,12 +233,12 @@ namespace System.Threading throw new ArgumentNullException(nameof(name), Environment.GetResourceString("ArgumentNull_WithParamName")); } - if(name.Length == 0) + if (name.Length == 0) { throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(name)); } #if !PLATFORM_UNIX - if(System.IO.Path.MaxPath < name.Length) + if (System.IO.Path.MaxPath < name.Length) { throw new ArgumentException(Environment.GetResourceString("Argument_WaitHandleNameTooLong", Path.MaxPath), nameof(name)); } @@ -262,7 +266,7 @@ namespace System.Threading } #endif - if(Win32Native.ERROR_FILE_NOT_FOUND == errorCode || Win32Native.ERROR_INVALID_NAME == errorCode) + if (Win32Native.ERROR_FILE_NOT_FOUND == errorCode || Win32Native.ERROR_INVALID_NAME == errorCode) return OpenExistingResult.NameNotFound; if (Win32Native.ERROR_PATH_NOT_FOUND == errorCode) return OpenExistingResult.PathNotFound; @@ -270,7 +274,7 @@ namespace System.Threading return OpenExistingResult.NameInvalid; // this is for passed through Win32Native Errors - __Error.WinIOError(errorCode,name); + __Error.WinIOError(errorCode, name); } result = new Mutex(myHandle); @@ -291,7 +295,7 @@ namespace System.Threading } } - static int CreateMutexHandle(bool initiallyOwned, String name, Win32Native.SECURITY_ATTRIBUTES securityAttribute, out SafeWaitHandle mutexHandle) + private static int CreateMutexHandle(bool initiallyOwned, String name, Win32Native.SECURITY_ATTRIBUTES securityAttribute, out SafeWaitHandle mutexHandle) { int errorCode; diff --git a/src/mscorlib/src/System/Threading/Overlapped.cs b/src/mscorlib/src/System/Threading/Overlapped.cs index fe55be73ea..8712c12c8f 100644 --- a/src/mscorlib/src/System/Threading/Overlapped.cs +++ b/src/mscorlib/src/System/Threading/Overlapped.cs @@ -24,18 +24,18 @@ =============================================================================*/ -namespace System.Threading -{ - using System; - using System.Runtime.InteropServices; - using System.Runtime.CompilerServices; - using System.Runtime.Versioning; - using System.Security; - using System.Runtime.ConstrainedExecution; - using System.Diagnostics; - using System.Diagnostics.Contracts; - using System.Collections.Concurrent; - +using System; +using System.Runtime.InteropServices; +using System.Runtime.CompilerServices; +using System.Runtime.Versioning; +using System.Security; +using System.Runtime.ConstrainedExecution; +using System.Diagnostics; +using System.Diagnostics.Contracts; +using System.Collections.Concurrent; + +namespace System.Threading +{ #region struct NativeOverlapped // Valuetype that represents the (unmanaged) Win32 OVERLAPPED structure @@ -45,11 +45,11 @@ namespace System.Threading [System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)] public struct NativeOverlapped { - public IntPtr InternalLow; - public IntPtr InternalHigh; - public int OffsetLow; - public int OffsetHigh; - public IntPtr EventHandle; + public IntPtr InternalLow; + public IntPtr InternalHigh; + public int OffsetLow; + public int OffsetHigh; + public IntPtr EventHandle; } #endregion struct NativeOverlapped @@ -59,11 +59,11 @@ namespace System.Threading unsafe internal class _IOCompletionCallback { - IOCompletionCallback _ioCompletionCallback; - ExecutionContext _executionContext; - uint _errorCode; // Error code - uint _numBytes; // No. of bytes transferred - NativeOverlapped* _pOVERLAP; + private IOCompletionCallback _ioCompletionCallback; + private ExecutionContext _executionContext; + private uint _errorCode; // Error code + private uint _numBytes; // No. of bytes transferred + private NativeOverlapped* _pOVERLAP; internal _IOCompletionCallback(IOCompletionCallback ioCompletionCallback) { @@ -75,12 +75,12 @@ namespace System.Threading static internal ContextCallback _ccb = new ContextCallback(IOCompletionCallback_Context); static internal void IOCompletionCallback_Context(Object state) { - _IOCompletionCallback helper = (_IOCompletionCallback)state; - Debug.Assert(helper != null,"_IOCompletionCallback cannot be null"); + _IOCompletionCallback helper = (_IOCompletionCallback)state; + Debug.Assert(helper != null, "_IOCompletionCallback cannot be null"); helper._ioCompletionCallback(helper._errorCode, helper._numBytes, helper._pOVERLAP); } - + // call back helper static unsafe internal void PerformIOCompletionCallback(uint errorCode, // Error code uint numBytes, // No. of bytes transferred @@ -93,13 +93,13 @@ namespace System.Threading do { overlapped = OverlappedData.GetOverlappedFromNative(pOVERLAP).m_overlapped; - helper = overlapped.iocbHelper; + helper = overlapped.iocbHelper; if (helper == null || helper._executionContext == null || helper._executionContext == ExecutionContext.Default) { // We got here because of UnsafePack (or) Pack with EC flow supressed IOCompletionCallback callback = overlapped.UserCallback; - callback( errorCode, numBytes, pOVERLAP); + callback(errorCode, numBytes, pOVERLAP); } else { @@ -108,12 +108,11 @@ namespace System.Threading helper._numBytes = numBytes; helper._pOVERLAP = pOVERLAP; ExecutionContext.Run(helper._executionContext, _ccb, helper); - } + } //Quickly check the VM again, to see if a packet has arrived. OverlappedData.CheckVMForIOPacket(out pOVERLAP, out errorCode, out numBytes); } while (pOVERLAP != null); - } } @@ -143,7 +142,7 @@ namespace System.Threading internal NativeOverlapped m_nativeOverlapped; // Adding an empty default ctor for annotation purposes - internal OverlappedData(){} + internal OverlappedData() { } internal void ReInitialize() { @@ -165,7 +164,8 @@ namespace System.Threading unsafe internal NativeOverlapped* Pack(IOCompletionCallback iocb, Object userData) { - if (!m_pinSelf.IsNull()) { + if (!m_pinSelf.IsNull()) + { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_Overlapped_Pack")); } @@ -195,8 +195,9 @@ namespace System.Threading } unsafe internal NativeOverlapped* UnsafePack(IOCompletionCallback iocb, Object userData) - { - if (!m_pinSelf.IsNull()) { + { + if (!m_pinSelf.IsNull()) + { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_Overlapped_Pack")); } m_userObject = userData; @@ -221,7 +222,7 @@ namespace System.Threading get { return m_nativeOverlapped.EventHandle; } set { m_nativeOverlapped.EventHandle = value; } } - + [MethodImplAttribute(MethodImplOptions.InternalCall)] unsafe private extern NativeOverlapped* AllocateNativeOverlapped(); @@ -229,7 +230,7 @@ namespace System.Threading unsafe internal static extern void FreeNativeOverlapped(NativeOverlapped* nativeOverlappedPtr); [MethodImplAttribute(MethodImplOptions.InternalCall)] - unsafe internal static extern OverlappedData GetOverlappedFromNative(NativeOverlapped* nativeOverlappedPtr); + unsafe internal static extern OverlappedData GetOverlappedFromNative(NativeOverlapped* nativeOverlappedPtr); [MethodImplAttribute(MethodImplOptions.InternalCall)] unsafe internal static extern void CheckVMForIOPacket(out NativeOverlapped* pOVERLAP, out uint errorCode, out uint numBytes); @@ -244,17 +245,17 @@ namespace System.Threading public class Overlapped { private OverlappedData m_overlappedData; - private static PinnableBufferCache s_overlappedDataCache = new PinnableBufferCache("System.Threading.OverlappedData", ()=> new OverlappedData()); - - public Overlapped() + private static PinnableBufferCache s_overlappedDataCache = new PinnableBufferCache("System.Threading.OverlappedData", () => new OverlappedData()); + + public Overlapped() { - m_overlappedData = (OverlappedData) s_overlappedDataCache.Allocate(); + m_overlappedData = (OverlappedData)s_overlappedDataCache.Allocate(); m_overlappedData.m_overlapped = this; } public Overlapped(int offsetLo, int offsetHi, IntPtr hEvent, IAsyncResult ar) { - m_overlappedData = (OverlappedData) s_overlappedDataCache.Allocate(); + m_overlappedData = (OverlappedData)s_overlappedDataCache.Allocate(); m_overlappedData.m_overlapped = this; m_overlappedData.m_nativeOverlapped.OffsetLow = offsetLo; m_overlappedData.m_nativeOverlapped.OffsetHigh = offsetHi; @@ -317,7 +318,7 @@ namespace System.Threading [CLSCompliant(false)] unsafe public NativeOverlapped* Pack(IOCompletionCallback iocb) { - return Pack (iocb, null); + return Pack(iocb, null); } [CLSCompliant(false)] @@ -330,12 +331,12 @@ namespace System.Threading [CLSCompliant(false)] unsafe public NativeOverlapped* UnsafePack(IOCompletionCallback iocb) { - return UnsafePack (iocb, null); + return UnsafePack(iocb, null); } [CLSCompliant(false)] unsafe public NativeOverlapped* UnsafePack(IOCompletionCallback iocb, Object userData) - { + { return m_overlappedData.UnsafePack(iocb, userData); } @@ -351,7 +352,7 @@ namespace System.Threading Contract.EndContractBlock(); Overlapped overlapped = OverlappedData.GetOverlappedFromNative(nativeOverlappedPtr).m_overlapped; - + return overlapped; } @@ -369,9 +370,7 @@ namespace System.Threading overlappedData.ReInitialize(); s_overlappedDataCache.Free(overlappedData); } - } #endregion class Overlapped - } // namespace diff --git a/src/mscorlib/src/System/Threading/ParameterizedThreadStart.cs b/src/mscorlib/src/System/Threading/ParameterizedThreadStart.cs index 32b63153c4..74f17a5d75 100644 --- a/src/mscorlib/src/System/Threading/ParameterizedThreadStart.cs +++ b/src/mscorlib/src/System/Threading/ParameterizedThreadStart.cs @@ -14,10 +14,11 @@ =============================================================================*/ -namespace System.Threading { - using System.Threading; - using System.Runtime.InteropServices; +using System.Threading; +using System.Runtime.InteropServices; +namespace System.Threading +{ [ComVisibleAttribute(false)] public delegate void ParameterizedThreadStart(object obj); } diff --git a/src/mscorlib/src/System/Threading/SemaphoreFullException.cs b/src/mscorlib/src/System/Threading/SemaphoreFullException.cs index 01c5040b7e..ca01dba07e 100644 --- a/src/mscorlib/src/System/Threading/SemaphoreFullException.cs +++ b/src/mscorlib/src/System/Threading/SemaphoreFullException.cs @@ -2,25 +2,30 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Threading { - using System; - using System.Runtime.Serialization; - using System.Runtime.InteropServices; +using System; +using System.Runtime.Serialization; +using System.Runtime.InteropServices; +namespace System.Threading +{ [Serializable] [ComVisibleAttribute(false)] - public class SemaphoreFullException : SystemException { - - public SemaphoreFullException() : base(Environment.GetResourceString("Threading_SemaphoreFullException")){ + public class SemaphoreFullException : SystemException + { + public SemaphoreFullException() : base(Environment.GetResourceString("Threading_SemaphoreFullException")) + { } - - public SemaphoreFullException(String message) : base(message) { + + public SemaphoreFullException(String message) : base(message) + { } - public SemaphoreFullException(String message, Exception innerException) : base(message, innerException) { + public SemaphoreFullException(String message, Exception innerException) : base(message, innerException) + { } - - protected SemaphoreFullException(SerializationInfo info, StreamingContext context) : base (info, context) { + + protected SemaphoreFullException(SerializationInfo info, StreamingContext context) : base(info, context) + { } } } diff --git a/src/mscorlib/src/System/Threading/SemaphoreSlim.cs b/src/mscorlib/src/System/Threading/SemaphoreSlim.cs index c3b43d9585..7be7d2fb55 100644 --- a/src/mscorlib/src/System/Threading/SemaphoreSlim.cs +++ b/src/mscorlib/src/System/Threading/SemaphoreSlim.cs @@ -21,6 +21,7 @@ using System.Diagnostics.Contracts; using System.Threading.Tasks; // The class will be part of the current System.Threading namespace + namespace System.Threading { /// <summary> @@ -84,7 +85,7 @@ namespace System.Threading private sealed class TaskNode : Task<bool>, IThreadPoolWorkItem { internal TaskNode Prev, Next; - internal TaskNode() : base() {} + internal TaskNode() : base() { } void IThreadPoolWorkItem.ExecuteWorkItem() { @@ -370,7 +371,7 @@ namespace System.Threading Debug.Assert(m_asyncTail != null, "tail should not be null if head isn't"); asyncWaitTask = WaitAsync(millisecondsTimeout, cancellationToken); } - // There are no async waiters, so we can proceed with normal synchronous waiting. + // There are no async waiters, so we can proceed with normal synchronous waiting. else { // If the count > 0 we are good to move on. @@ -399,7 +400,7 @@ namespace System.Threading // defer to synchronous waiters in priority, which means that if it's possible an asynchronous // waiter didn't get released because a synchronous waiter was present, we need to ensure // that synchronous waiter succeeds so that they have a chance to release. - Debug.Assert(!waitSuccessful || m_currentCount > 0, + Debug.Assert(!waitSuccessful || m_currentCount > 0, "If the wait was successful, there should be count available."); if (m_currentCount > 0) { @@ -628,9 +629,9 @@ namespace System.Threading // No counts, if timeout is zero fail fast return s_falseTask; } - // If there aren't, create and return a task to the caller. - // The task will be completed either when they've successfully acquired - // the semaphore or when the timeout expired or cancellation was requested. + // If there aren't, create and return a task to the caller. + // The task will be completed either when they've successfully acquired + // the semaphore or when the timeout expired or cancellation was requested. else { Debug.Assert(m_currentCount == 0, "m_currentCount should never be negative"); @@ -882,7 +883,7 @@ namespace System.Threading } - + /// <summary> /// Private helper method to wake up waiters when a cancellationToken gets canceled. /// </summary> diff --git a/src/mscorlib/src/System/Threading/SendOrPostCallback.cs b/src/mscorlib/src/System/Threading/SendOrPostCallback.cs index b81d2bff64..c08b1aba6e 100644 --- a/src/mscorlib/src/System/Threading/SendOrPostCallback.cs +++ b/src/mscorlib/src/System/Threading/SendOrPostCallback.cs @@ -11,6 +11,6 @@ ===========================================================*/ namespace System.Threading -{ +{ public delegate void SendOrPostCallback(Object state); } diff --git a/src/mscorlib/src/System/Threading/SpinWait.cs b/src/mscorlib/src/System/Threading/SpinWait.cs index 8431f6564f..e5bd3c71c2 100644 --- a/src/mscorlib/src/System/Threading/SpinWait.cs +++ b/src/mscorlib/src/System/Threading/SpinWait.cs @@ -71,7 +71,6 @@ namespace System.Threading /// </remarks> public struct SpinWait { - // These constants determine the frequency of yields versus spinning. The // numbers may seem fairly arbitrary, but were derived with at least some // thought in the design document. I fully expect they will need to change @@ -188,7 +187,7 @@ namespace System.Threading public static void SpinUntil(Func<bool> condition) { #if DEBUG - bool result = + bool result = #endif SpinUntil(condition, Timeout.Infinite); #if DEBUG @@ -267,7 +266,6 @@ namespace System.Threading } } return true; - } #endregion @@ -360,5 +358,4 @@ namespace System.Threading return currentWaitTimeout; } } - } diff --git a/src/mscorlib/src/System/Threading/SynchronizationContext.cs b/src/mscorlib/src/System/Threading/SynchronizationContext.cs index f4b3c79409..676a198ee7 100644 --- a/src/mscorlib/src/System/Threading/SynchronizationContext.cs +++ b/src/mscorlib/src/System/Threading/SynchronizationContext.cs @@ -11,7 +11,7 @@ ===========================================================*/ namespace System.Threading -{ +{ using Microsoft.Win32.SafeHandles; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; @@ -27,7 +27,7 @@ namespace System.Threading [Flags] - enum SynchronizationContextProperties + internal enum SynchronizationContextProperties { None = 0, RequireWaitNotification = 0x1 @@ -41,27 +41,27 @@ namespace System.Threading [FriendAccessAllowed] internal class WinRTSynchronizationContextFactoryBase { - public virtual SynchronizationContext Create(object coreDispatcher) {return null;} + public virtual SynchronizationContext Create(object coreDispatcher) { return null; } } #endif //FEATURE_COMINTEROP public class SynchronizationContext { - SynchronizationContextProperties _props = SynchronizationContextProperties.None; - + private SynchronizationContextProperties _props = SynchronizationContextProperties.None; + public SynchronizationContext() { } - + // helper delegate to statically bind to Wait method private delegate int WaitDelegate(IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout); - static Type s_cachedPreparedType1; - static Type s_cachedPreparedType2; - static Type s_cachedPreparedType3; - static Type s_cachedPreparedType4; - static Type s_cachedPreparedType5; + private static Type s_cachedPreparedType1; + private static Type s_cachedPreparedType2; + private static Type s_cachedPreparedType3; + private static Type s_cachedPreparedType4; + private static Type s_cachedPreparedType5; // protected so that only the derived sync context class can enable these flags [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "We never dereference s_cachedPreparedType*, so ordering is unimportant")] @@ -87,11 +87,11 @@ namespace System.Threading { RuntimeHelpers.PrepareDelegate(new WaitDelegate(this.Wait)); - if (s_cachedPreparedType1 == null) s_cachedPreparedType1 = type; - else if (s_cachedPreparedType2 == null) s_cachedPreparedType2 = type; - else if (s_cachedPreparedType3 == null) s_cachedPreparedType3 = type; - else if (s_cachedPreparedType4 == null) s_cachedPreparedType4 = type; - else if (s_cachedPreparedType5 == null) s_cachedPreparedType5 = type; + if (s_cachedPreparedType1 == null) s_cachedPreparedType1 = type; + else if (s_cachedPreparedType2 == null) s_cachedPreparedType2 = type; + else if (s_cachedPreparedType3 == null) s_cachedPreparedType3 = type; + else if (s_cachedPreparedType4 == null) s_cachedPreparedType4 = type; + else if (s_cachedPreparedType5 == null) s_cachedPreparedType5 = type; } _props |= SynchronizationContextProperties.RequireWaitNotification; @@ -99,10 +99,10 @@ namespace System.Threading public bool IsWaitNotificationRequired() { - return ((_props & SynchronizationContextProperties.RequireWaitNotification) != 0); + return ((_props & SynchronizationContextProperties.RequireWaitNotification) != 0); } - + public virtual void Send(SendOrPostCallback d, Object state) { d(state); @@ -113,7 +113,7 @@ namespace System.Threading ThreadPool.QueueUserWorkItem(new WaitCallback(d), state); } - + /// <summary> /// Optional override for subclasses, for responding to notification that operation is starting. /// </summary> @@ -159,9 +159,9 @@ namespace System.Threading Thread.CurrentThread.SynchronizationContext = syncContext; } - public static SynchronizationContext Current + public static SynchronizationContext Current { - get + get { SynchronizationContext context = Thread.CurrentThread.SynchronizationContext; @@ -189,7 +189,7 @@ namespace System.Threading { Debug.Assert(Environment.IsWinRTSupported); Debug.Assert(AppDomain.IsAppXModel()); - + // // We call into the VM to get the dispatcher. This is because: // @@ -207,7 +207,7 @@ namespace System.Threading return null; } - static WinRTSynchronizationContextFactoryBase s_winRTContextFactory; + private static WinRTSynchronizationContextFactoryBase s_winRTContextFactory; private static WinRTSynchronizationContextFactoryBase GetWinRTSynchronizationContextFactory() { diff --git a/src/mscorlib/src/System/Threading/SynchronizationLockException.cs b/src/mscorlib/src/System/Threading/SynchronizationLockException.cs index de42c1f232..1f7a284ff4 100644 --- a/src/mscorlib/src/System/Threading/SynchronizationLockException.cs +++ b/src/mscorlib/src/System/Threading/SynchronizationLockException.cs @@ -13,31 +13,37 @@ ** =============================================================================*/ -namespace System.Threading { - using System; - using System.Runtime.Serialization; +using System; +using System.Runtime.Serialization; + +namespace System.Threading +{ [Serializable] - public class SynchronizationLockException : SystemException { - public SynchronizationLockException() - : base(Environment.GetResourceString("Arg_SynchronizationLockException")) { + public class SynchronizationLockException : SystemException + { + public SynchronizationLockException() + : base(Environment.GetResourceString("Arg_SynchronizationLockException")) + { SetErrorCode(__HResults.COR_E_SYNCHRONIZATIONLOCK); } - - public SynchronizationLockException(String message) - : base(message) { + + public SynchronizationLockException(String message) + : base(message) + { SetErrorCode(__HResults.COR_E_SYNCHRONIZATIONLOCK); } - - public SynchronizationLockException(String message, Exception innerException) - : base(message, innerException) { + + public SynchronizationLockException(String message, Exception innerException) + : base(message, innerException) + { SetErrorCode(__HResults.COR_E_SYNCHRONIZATIONLOCK); } - protected SynchronizationLockException(SerializationInfo info, StreamingContext context) : base (info, context) { + protected SynchronizationLockException(SerializationInfo info, StreamingContext context) : base(info, context) + { } } - } diff --git a/src/mscorlib/src/System/Threading/Tasks/AsyncCausalityTracer.cs b/src/mscorlib/src/System/Threading/Tasks/AsyncCausalityTracer.cs index ec7c5aaeea..ec154f9efb 100644 --- a/src/mscorlib/src/System/Threading/Tasks/AsyncCausalityTracer.cs +++ b/src/mscorlib/src/System/Threading/Tasks/AsyncCausalityTracer.cs @@ -21,7 +21,6 @@ using WFD = Windows.Foundation.Diagnostics; namespace System.Threading.Tasks { - [FriendAccessAllowed] internal enum CausalityTraceLevel { @@ -85,13 +84,13 @@ namespace System.Threading.Tasks [FriendAccessAllowed] internal static class AsyncCausalityTracer { - static internal void EnableToETW(bool enabled) + static internal void EnableToETW(bool enabled) { #if FEATURE_COMINTEROP if (enabled) - f_LoggingOn |= Loggers.ETW; - else - f_LoggingOn &= ~Loggers.ETW; + f_LoggingOn |= Loggers.ETW; + else + f_LoggingOn &= ~Loggers.ETW; #endif } @@ -121,7 +120,8 @@ namespace System.Threading.Tasks // The loggers that this Tracer knows about. [Flags] - private enum Loggers : byte { + private enum Loggers : byte + { CausalityTracer = 1, ETW = 2 } @@ -148,7 +148,7 @@ namespace System.Threading.Tasks int hresult = Microsoft.Win32.UnsafeNativeMethods.RoGetActivationFactory(ClassId, ref guid, out factory); if (hresult < 0 || factory == null) return; //This prevents having an exception thrown in case IAsyncCausalityTracerStatics isn't registered. - + s_TracerFactory = (WFD.IAsyncCausalityTracerStatics)factory; EventRegistrationToken token = s_TracerFactory.add_TracingStatusChanged(new EventHandler<WFD.TracingStatusChangedEventArgs>(TracingStatusChangedHandler)); @@ -161,15 +161,14 @@ namespace System.Threading.Tasks // doing here depends on internal state. LogAndDisable(ex); } - } private static void TracingStatusChangedHandler(Object sender, WFD.TracingStatusChangedEventArgs args) { if (args.Enabled) - f_LoggingOn |= Loggers.CausalityTracer; - else - f_LoggingOn &= ~Loggers.CausalityTracer; + f_LoggingOn |= Loggers.CausalityTracer; + else + f_LoggingOn &= ~Loggers.CausalityTracer; } #endif @@ -185,11 +184,11 @@ namespace System.Threading.Tasks try { if ((f_LoggingOn & Loggers.ETW) != 0) - TplEtwProvider.Log.TraceOperationBegin(taskId, operationName, (long) relatedContext); + TplEtwProvider.Log.TraceOperationBegin(taskId, operationName, (long)relatedContext); if ((f_LoggingOn & Loggers.CausalityTracer) != 0) s_TracerFactory.TraceOperationCreation((WFD.CausalityTraceLevel)traceLevel, s_CausalitySource, s_PlatformId, GetOperationId((uint)taskId), operationName, relatedContext); } - catch(Exception ex) + catch (Exception ex) { //view function comment LogAndDisable(ex); @@ -209,7 +208,7 @@ namespace System.Threading.Tasks if ((f_LoggingOn & Loggers.CausalityTracer) != 0) s_TracerFactory.TraceOperationCompletion((WFD.CausalityTraceLevel)traceLevel, s_CausalitySource, s_PlatformId, GetOperationId((uint)taskId), (WFD.AsyncCausalityStatus)status); } - catch(Exception ex) + catch (Exception ex) { //view function comment LogAndDisable(ex); @@ -228,7 +227,7 @@ namespace System.Threading.Tasks if ((f_LoggingOn & Loggers.CausalityTracer) != 0) s_TracerFactory.TraceOperationRelation((WFD.CausalityTraceLevel)traceLevel, s_CausalitySource, s_PlatformId, GetOperationId((uint)taskId), (WFD.CausalityRelation)relation); } - catch(Exception ex) + catch (Exception ex) { //view function comment LogAndDisable(ex); @@ -247,7 +246,7 @@ namespace System.Threading.Tasks if ((f_LoggingOn & Loggers.CausalityTracer) != 0) s_TracerFactory.TraceSynchronousWorkStart((WFD.CausalityTraceLevel)traceLevel, s_CausalitySource, s_PlatformId, GetOperationId((uint)taskId), (WFD.CausalitySynchronousWork)work); } - catch(Exception ex) + catch (Exception ex) { //view function comment LogAndDisable(ex); @@ -266,7 +265,7 @@ namespace System.Threading.Tasks if ((f_LoggingOn & Loggers.CausalityTracer) != 0) s_TracerFactory.TraceSynchronousWorkCompletion((WFD.CausalityTraceLevel)traceLevel, s_CausalitySource, (WFD.CausalitySynchronousWork)work); } - catch(Exception ex) + catch (Exception ex) { //view function comment LogAndDisable(ex); @@ -288,6 +287,5 @@ namespace System.Threading.Tasks { return (((ulong)AppDomain.CurrentDomain.Id) << 32) + taskId; } - } } diff --git a/src/mscorlib/src/System/Threading/Tasks/ConcurrentExclusiveSchedulerPair.cs b/src/mscorlib/src/System/Threading/Tasks/ConcurrentExclusiveSchedulerPair.cs index a87406a493..07a673bf4e 100644 --- a/src/mscorlib/src/System/Threading/Tasks/ConcurrentExclusiveSchedulerPair.cs +++ b/src/mscorlib/src/System/Threading/Tasks/ConcurrentExclusiveSchedulerPair.cs @@ -72,22 +72,25 @@ namespace System.Threading.Tasks /// Initializes the ConcurrentExclusiveSchedulerPair. /// </summary> public ConcurrentExclusiveSchedulerPair() : - this(TaskScheduler.Default, DefaultMaxConcurrencyLevel, DEFAULT_MAXITEMSPERTASK) { } + this(TaskScheduler.Default, DefaultMaxConcurrencyLevel, DEFAULT_MAXITEMSPERTASK) + { } /// <summary> /// Initializes the ConcurrentExclusiveSchedulerPair to target the specified scheduler. /// </summary> /// <param name="taskScheduler">The target scheduler on which this pair should execute.</param> public ConcurrentExclusiveSchedulerPair(TaskScheduler taskScheduler) : - this(taskScheduler, DefaultMaxConcurrencyLevel, DEFAULT_MAXITEMSPERTASK) { } + this(taskScheduler, DefaultMaxConcurrencyLevel, DEFAULT_MAXITEMSPERTASK) + { } /// <summary> /// Initializes the ConcurrentExclusiveSchedulerPair to target the specified scheduler with a maximum concurrency level. /// </summary> /// <param name="taskScheduler">The target scheduler on which this pair should execute.</param> /// <param name="maxConcurrencyLevel">The maximum number of tasks to run concurrently.</param> - public ConcurrentExclusiveSchedulerPair(TaskScheduler taskScheduler, int maxConcurrencyLevel) : - this(taskScheduler, maxConcurrencyLevel, DEFAULT_MAXITEMSPERTASK) { } + public ConcurrentExclusiveSchedulerPair(TaskScheduler taskScheduler, int maxConcurrencyLevel) : + this(taskScheduler, maxConcurrencyLevel, DEFAULT_MAXITEMSPERTASK) + { } /// <summary> /// Initializes the ConcurrentExclusiveSchedulerPair to target the specified scheduler with a maximum @@ -141,7 +144,7 @@ namespace System.Threading.Tasks } /// <summary>Gets a <see cref="System.Threading.Tasks.Task"/> that will complete when the scheduler has completed processing.</summary> - public Task Completion + public Task Completion { // ValueLock not needed, but it's ok if it's held get { return EnsureCompletionStateInitialized().Task; } @@ -162,7 +165,7 @@ namespace System.Threading.Tasks } /// <summary>Sets that completion has been requested.</summary> - private void RequestCompletion() + private void RequestCompletion() { ContractAssertMonitorStatus(ValueLock, held: true); EnsureCompletionStateInitialized().m_completionRequested = true; @@ -190,9 +193,9 @@ namespace System.Threading.Tasks // Now, only allow shutdown if an exception occurred or if there are no more tasks to process. var cs = EnsureCompletionStateInitialized(); - return + return (cs.m_exceptions != null && cs.m_exceptions.Count > 0) || - (m_concurrentTaskScheduler.m_tasks.IsEmpty && m_exclusiveTaskScheduler.m_tasks.IsEmpty); + (m_concurrentTaskScheduler.m_tasks.IsEmpty && m_exclusiveTaskScheduler.m_tasks.IsEmpty); } } @@ -330,7 +333,7 @@ namespace System.Threading.Tasks } } } - + // Check to see if all tasks have completed and if completion has been requested. CleanupStateIfCompletingAndQuiesced(); } @@ -370,7 +373,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); - Debug.Assert(currentMode == ProcessingMode.ProcessingExclusiveTask, + Debug.Assert(currentMode == ProcessingMode.ProcessingExclusiveTask, "Somehow we ended up escaping exclusive mode."); lock (ValueLock) @@ -720,7 +723,7 @@ namespace System.Threading.Tasks return mode; } } - + /// <summary>Asserts that a given synchronization object is either held or not held.</summary> /// <param name="syncObj">The monitor to check.</param> /// <param name="held">Whether we want to assert that it's currently held or not held.</param> @@ -748,7 +751,7 @@ namespace System.Threading.Tasks Debug.Assert(Monitor.IsEntered(syncObj) == held, "The locking scheme was not correctly followed."); #endif } - + /// <summary>Gets the options to use for tasks.</summary> /// <param name="isReplacementReplica">If this task is being created to replace another.</param> /// <remarks> @@ -758,7 +761,7 @@ namespace System.Threading.Tasks /// <returns>The options to use.</returns> internal static TaskCreationOptions GetCreationOptionsForTask(bool isReplacementReplica = false) { - TaskCreationOptions options = + TaskCreationOptions options = #if PRENET45 TaskCreationOptions.None; #else @@ -784,5 +787,4 @@ namespace System.Threading.Tasks Completed = 0x8 } } - } diff --git a/src/mscorlib/src/System/Threading/Tasks/FutureFactory.cs b/src/mscorlib/src/System/Threading/Tasks/FutureFactory.cs index 137afa11f5..60a7c81dcf 100644 --- a/src/mscorlib/src/System/Threading/Tasks/FutureFactory.cs +++ b/src/mscorlib/src/System/Threading/Tasks/FutureFactory.cs @@ -568,8 +568,6 @@ namespace System.Threading.Tasks promise.DangerousSetResult(result); } } - - } } @@ -691,7 +689,7 @@ namespace System.Threading.Tasks // RespectParentCancellation. Task t = new Task(new Action<object>(delegate { - FromAsyncCoreLogic(asyncResult, endFunction, endAction, promise, requiresSynchronization:true); + FromAsyncCoreLogic(asyncResult, endFunction, endAction, promise, requiresSynchronization: true); }), (object)null, null, default(CancellationToken), TaskCreationOptions.None, InternalTaskOptions.None, null); @@ -706,7 +704,7 @@ namespace System.Threading.Tasks if (asyncResult.IsCompleted) { - try { t.InternalRunSynchronously(scheduler, waitForCompletion:false); } + try { t.InternalRunSynchronously(scheduler, waitForCompletion: false); } catch (Exception e) { promise.TrySetException(e); } // catch and log any scheduler exceptions } else @@ -792,7 +790,7 @@ namespace System.Threading.Tasks ThrowHelper.ThrowArgumentNullException(ExceptionArgument.endMethod); Contract.Requires((endFunction != null) != (endAction != null), "Both endFunction and endAction were non-null"); - + TaskFactory.CheckFromAsyncOptions(creationOptions, true); Task<TResult> promise = new Task<TResult>(state, creationOptions); @@ -943,7 +941,6 @@ namespace System.Threading.Tasks } catch { - if (AsyncCausalityTracer.LoggingOn) AsyncCausalityTracer.TraceOperationCompletion(CausalityTraceLevel.Required, promise.Id, AsyncCausalityStatus.Error); @@ -1241,7 +1238,7 @@ namespace System.Threading.Tasks internal static Task<TResult> FromAsyncTrim<TInstance, TArgs>( TInstance thisRef, TArgs args, Func<TInstance, TArgs, AsyncCallback, object, IAsyncResult> beginMethod, - Func<TInstance, IAsyncResult, TResult> endMethod) + Func<TInstance, IAsyncResult, TResult> endMethod) where TInstance : class { // Validate arguments, but only with asserts, as this is an internal only implementation. @@ -1319,7 +1316,7 @@ namespace System.Threading.Tasks // we'll instead complete the promise at the call site. if (!asyncResult.CompletedSynchronously) { - promise.Complete(thisRef, endMethod, asyncResult, requiresSynchronization:true); + promise.Complete(thisRef, endMethod, asyncResult, requiresSynchronization: true); } } @@ -1661,7 +1658,7 @@ namespace System.Threading.Tasks return ContinueWhenAllImpl<TAntecedentResult>(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler); } - + // Core implementation of ContinueWhenAll -- the generic version // Note: if you make any changes to this method, please do the same to the non-generic version too. internal static Task<TResult> ContinueWhenAllImpl<TAntecedentResult>(Task<TAntecedentResult>[] tasks, @@ -1744,10 +1741,10 @@ namespace System.Threading.Tasks //the following delegate avoids closure capture as much as possible //completedTasks.Result == tasksCopy; //state == continuationFunction - (completedTasks, state) => + (completedTasks, state) => { completedTasks.NotifyDebuggerOfWaitCompletionIfNecessary(); - return ((Func<Task[], TResult>)state)(completedTasks.Result); + return ((Func<Task[], TResult>)state)(completedTasks.Result); }, continuationFunction, scheduler, cancellationToken, continuationOptions); } @@ -1755,13 +1752,13 @@ namespace System.Threading.Tasks { Debug.Assert(continuationAction != null); return starter.ContinueWith<TResult>( - //the following delegate avoids closure capture as much as possible - //completedTasks.Result == tasksCopy; - //state == continuationAction - (completedTasks, state) => + //the following delegate avoids closure capture as much as possible + //completedTasks.Result == tasksCopy; + //state == continuationAction + (completedTasks, state) => { completedTasks.NotifyDebuggerOfWaitCompletionIfNecessary(); - ((Action<Task[]>)state)(completedTasks.Result); return default(TResult); + ((Action<Task[]>)state)(completedTasks.Result); return default(TResult); }, continuationAction, scheduler, cancellationToken, continuationOptions); } @@ -2054,7 +2051,7 @@ namespace System.Threading.Tasks // check arguments TaskFactory.CheckMultiTaskContinuationOptions(continuationOptions); if (tasks == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.tasks); - if(tasks.Length == 0) ThrowHelper.ThrowArgumentException( ExceptionResource.Task_MultiTaskContinuation_EmptyTaskList, ExceptionArgument.tasks); + if (tasks.Length == 0) ThrowHelper.ThrowArgumentException(ExceptionResource.Task_MultiTaskContinuation_EmptyTaskList, ExceptionArgument.tasks); //ArgumentNullException of continuationFunction or continuationAction is checked by the caller Contract.Requires((continuationFunction != null) != (continuationAction != null), "Expected exactly one of endFunction/endAction to be non-null"); @@ -2076,8 +2073,8 @@ namespace System.Threading.Tasks if (continuationFunction != null) { return starter.ContinueWith( - //the following delegate avoids closure capture as much as possible - //completedTask.Result is the winning task; state == continuationAction + //the following delegate avoids closure capture as much as possible + //completedTask.Result is the winning task; state == continuationAction (completedTask, state) => { return ((Func<Task, TResult>)state)(completedTask.Result); }, continuationFunction, scheduler, cancellationToken, continuationOptions); } @@ -2132,7 +2129,7 @@ namespace System.Threading.Tasks Debug.Assert(continuationAction != null); return starter.ContinueWith<TResult>( // Use a cached delegate - GenericDelegateCache<TAntecedentResult,TResult>.CWAnyActionDelegate, + GenericDelegateCache<TAntecedentResult, TResult>.CWAnyActionDelegate, continuationAction, scheduler, cancellationToken, continuationOptions); } } @@ -2180,7 +2177,5 @@ namespace System.Threading.Tasks action(wrappedAntecedents.Result); return default(TResult); }; - } - } diff --git a/src/mscorlib/src/System/Threading/Tasks/IAsyncCausalityTracerStatics.cs b/src/mscorlib/src/System/Threading/Tasks/IAsyncCausalityTracerStatics.cs index 32efd771a0..17dd1f8bde 100644 --- a/src/mscorlib/src/System/Threading/Tasks/IAsyncCausalityTracerStatics.cs +++ b/src/mscorlib/src/System/Threading/Tasks/IAsyncCausalityTracerStatics.cs @@ -13,6 +13,7 @@ using System.Runtime.InteropServices.WindowsRuntime; // Windows.Foundation.Diagnostics cannot be referenced from managed code because // they're hidden by the metadata adapter. We redeclare the interfaces manually // to be able to talk to native WinRT objects. + namespace Windows.Foundation.Diagnostics { [ComImport] @@ -47,16 +48,16 @@ namespace Windows.Foundation.Diagnostics [WindowsRuntimeImport] internal sealed class TracingStatusChangedEventArgs : ITracingStatusChangedEventArgs { - public extern bool Enabled + public extern bool Enabled { [MethodImpl(MethodImplOptions.InternalCall)] get; } - - public extern CausalityTraceLevel TraceLevel + + public extern CausalityTraceLevel TraceLevel { [MethodImpl(MethodImplOptions.InternalCall)] - get; + get; } } @@ -97,5 +98,4 @@ namespace Windows.Foundation.Diagnostics Error = 3, Started = 0 } - } diff --git a/src/mscorlib/src/System/Threading/Tasks/ProducerConsumerQueues.cs b/src/mscorlib/src/System/Threading/Tasks/ProducerConsumerQueues.cs index 545bf9a5e5..f9d5f89398 100644 --- a/src/mscorlib/src/System/Threading/Tasks/ProducerConsumerQueues.cs +++ b/src/mscorlib/src/System/Threading/Tasks/ProducerConsumerQueues.cs @@ -182,7 +182,8 @@ namespace System.Threading.Tasks newSegment.m_state.m_last = 1; newSegment.m_state.m_lastCopy = 1; - try { } finally + try { } + finally { // Finally block to protect against corruption due to a thread abort // between setting m_next and setting m_tail. @@ -271,8 +272,8 @@ namespace System.Threading.Tasks { for (Segment segment = m_head; segment != null; segment = segment.m_next) { - for (int pt = segment.m_state.m_first; - pt != segment.m_state.m_last; + for (int pt = segment.m_state.m_first; + pt != segment.m_state.m_last; pt = (pt + 1) & (segment.m_array.Length - 1)) { yield return segment.m_array[pt]; @@ -307,7 +308,7 @@ namespace System.Threading.Tasks } /// <summary>A segment in the queue containing one or more items.</summary> - [StructLayout(LayoutKind.Sequential)] + [StructLayout(LayoutKind.Sequential)] private sealed class Segment { /// <summary>The next segment in the linked list of segments.</summary> @@ -367,7 +368,7 @@ namespace System.Threading.Tasks } /// <summary>A placeholder class for common padding constants and eventually routines.</summary> - static class PaddingHelpers + internal static class PaddingHelpers { /// <summary>A size greater than or equal to the size of the most common CPU cache lines.</summary> internal const int CACHE_LINE_SIZE = 128; @@ -375,8 +376,7 @@ namespace System.Threading.Tasks /// <summary>Padding structure used to minimize false sharing in SingleProducerSingleConsumerQueue{T}.</summary> [StructLayout(LayoutKind.Explicit, Size = PaddingHelpers.CACHE_LINE_SIZE - sizeof(Int32))] // Based on common case of 64-byte cache lines - struct PaddingFor32 + internal struct PaddingFor32 { } - } diff --git a/src/mscorlib/src/System/Threading/Tasks/TPLETWProvider.cs b/src/mscorlib/src/System/Threading/Tasks/TPLETWProvider.cs index 12cc1daa63..19430596be 100644 --- a/src/mscorlib/src/System/Threading/Tasks/TPLETWProvider.cs +++ b/src/mscorlib/src/System/Threading/Tasks/TPLETWProvider.cs @@ -16,21 +16,21 @@ using System.Text; using System.Security; using System.Runtime.CompilerServices; +using System.Diagnostics.Tracing; + namespace System.Threading.Tasks { - using System.Diagnostics.Tracing; - /// <summary>Provides an event source for tracing TPL information.</summary> [EventSource( Name = "System.Threading.Tasks.TplEventSource", - Guid = "2e5dba47-a3d2-4d16-8ee0-6671ffdcd7b5", + Guid = "2e5dba47-a3d2-4d16-8ee0-6671ffdcd7b5", LocalizationResources = System.CoreLib.Name)] internal sealed class TplEtwProvider : EventSource { /// Used to determine if tasks should generate Activity IDs for themselves internal bool TasksSetActivityIds; // This keyword is set internal bool Debug; - private bool DebugActivityId; + private bool DebugActivityId; /// <summary> /// Get callbacks when the ETW sends us commands` @@ -42,11 +42,11 @@ namespace System.Threading.Tasks AsyncCausalityTracer.EnableToETW(true); else if (command.Command == EventCommand.Disable) AsyncCausalityTracer.EnableToETW(false); - - if (IsEnabled(EventLevel.Informational, Keywords.TasksFlowActivityIds)) + + if (IsEnabled(EventLevel.Informational, Keywords.TasksFlowActivityIds)) ActivityTracker.Instance.Enable(); - else - TasksSetActivityIds = IsEnabled(EventLevel.Informational, Keywords.TasksSetActivityIds); + else + TasksSetActivityIds = IsEnabled(EventLevel.Informational, Keywords.TasksSetActivityIds); Debug = IsEnabled(EventLevel.Informational, Keywords.Debug); DebugActivityId = IsEnabled(EventLevel.Informational, Keywords.DebugActivityId); @@ -99,49 +99,49 @@ namespace System.Threading.Tasks /// This sets activity IDS and logs when tasks are schedules (or waits begin) /// But are otherwise silent /// </summary> - public const EventKeywords TaskTransfer = (EventKeywords) 1; + public const EventKeywords TaskTransfer = (EventKeywords)1; /// <summary> /// TaskTranser events plus events when tasks start and stop /// </summary> - public const EventKeywords Tasks = (EventKeywords) 2; + public const EventKeywords Tasks = (EventKeywords)2; /// <summary> /// Events associted with the higher level parallel APIs /// </summary> - public const EventKeywords Parallel = (EventKeywords) 4; + public const EventKeywords Parallel = (EventKeywords)4; /// <summary> /// These are relatively verbose events that effectively just redirect /// the windows AsyncCausalityTracer to ETW /// </summary> - public const EventKeywords AsyncCausalityOperation = (EventKeywords) 8; - public const EventKeywords AsyncCausalityRelation = (EventKeywords) 0x10; - public const EventKeywords AsyncCausalitySynchronousWork = (EventKeywords) 0x20; + public const EventKeywords AsyncCausalityOperation = (EventKeywords)8; + public const EventKeywords AsyncCausalityRelation = (EventKeywords)0x10; + public const EventKeywords AsyncCausalitySynchronousWork = (EventKeywords)0x20; /// <summary> /// Emit the stops as well as the schedule/start events /// </summary> - public const EventKeywords TaskStops = (EventKeywords) 0x40; + public const EventKeywords TaskStops = (EventKeywords)0x40; /// <summary> /// TasksFlowActivityIds indicate that activity ID flow from one task /// to any task created by it. /// </summary> - public const EventKeywords TasksFlowActivityIds = (EventKeywords) 0x80; + public const EventKeywords TasksFlowActivityIds = (EventKeywords)0x80; /// <summary> /// TasksSetActivityIds will cause the task operations to set Activity Ids /// This option is incompatible with TasksFlowActivityIds flow is ignored /// if that keyword is set. This option is likley to be removed in the future /// </summary> - public const EventKeywords TasksSetActivityIds = (EventKeywords) 0x10000; + public const EventKeywords TasksSetActivityIds = (EventKeywords)0x10000; /// <summary> /// Relatively Verbose logging meant for debugging the Task library itself. Will probably be removed in the future /// </summary> - public const EventKeywords Debug = (EventKeywords) 0x20000; + public const EventKeywords Debug = (EventKeywords)0x20000; /// <summary> /// Relatively Verbose logging meant for debugging the Task library itself. Will probably be removed in the future /// </summary> - public const EventKeywords DebugActivityId = (EventKeywords) 0x40000; + public const EventKeywords DebugActivityId = (EventKeywords)0x40000; } /// <summary>Enabled for all keywords.</summary> @@ -182,18 +182,18 @@ namespace System.Threading.Tasks /// <summary>A continuation of a taskWaitEnd is complete </summary> private const int TASKWAITCONTINUATIONSTARTED_ID = 19; - private const int TRACEOPERATIONSTART_ID = 14; - private const int TRACEOPERATIONSTOP_ID = 15; - private const int TRACEOPERATIONRELATION_ID = 16; + private const int TRACEOPERATIONSTART_ID = 14; + private const int TRACEOPERATIONSTOP_ID = 15; + private const int TRACEOPERATIONRELATION_ID = 16; private const int TRACESYNCHRONOUSWORKSTART_ID = 17; - private const int TRACESYNCHRONOUSWORKSTOP_ID = 18; + private const int TRACESYNCHRONOUSWORKSTOP_ID = 18; + - //----------------------------------------------------------------------------------- // // Task Events // - + // These are all verbose events, so we need to call IsEnabled(EventLevel.Verbose, ALL_KEYWORDS) // call. However since the IsEnabled(l,k) call is more expensive than IsEnabled(), we only want // to incur this cost when instrumentation is enabled. So the Task codepaths that call these @@ -208,36 +208,36 @@ 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> - [Event(TASKSCHEDULED_ID, Task = Tasks.TaskScheduled, Version=1, Opcode = EventOpcode.Send, - Level = EventLevel.Informational, Keywords = Keywords.TaskTransfer|Keywords.Tasks)] + [Event(TASKSCHEDULED_ID, Task = Tasks.TaskScheduled, Version = 1, Opcode = EventOpcode.Send, + Level = EventLevel.Informational, Keywords = Keywords.TaskTransfer | Keywords.Tasks)] public void TaskScheduled( int OriginatingTaskSchedulerID, int OriginatingTaskID, // PFX_COMMON_EVENT_HEADER int TaskID, int CreatingTaskID, int TaskCreationOptions, int appDomain) { // IsEnabled() call is an inlined quick check that makes this very fast when provider is off - if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.TaskTransfer|Keywords.Tasks)) + if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.TaskTransfer | Keywords.Tasks)) { unsafe { EventData* eventPayload = stackalloc EventData[6]; eventPayload[0].Size = sizeof(int); - eventPayload[0].DataPointer = ((IntPtr) (&OriginatingTaskSchedulerID)); + eventPayload[0].DataPointer = ((IntPtr)(&OriginatingTaskSchedulerID)); eventPayload[1].Size = sizeof(int); - eventPayload[1].DataPointer = ((IntPtr) (&OriginatingTaskID)); + eventPayload[1].DataPointer = ((IntPtr)(&OriginatingTaskID)); eventPayload[2].Size = sizeof(int); - eventPayload[2].DataPointer = ((IntPtr) (&TaskID)); + eventPayload[2].DataPointer = ((IntPtr)(&TaskID)); eventPayload[3].Size = sizeof(int); - eventPayload[3].DataPointer = ((IntPtr) (&CreatingTaskID)); + eventPayload[3].DataPointer = ((IntPtr)(&CreatingTaskID)); eventPayload[4].Size = sizeof(int); - eventPayload[4].DataPointer = ((IntPtr) (&TaskCreationOptions)); + eventPayload[4].DataPointer = ((IntPtr)(&TaskCreationOptions)); eventPayload[5].Size = sizeof(int); - eventPayload[5].DataPointer = ((IntPtr) (&appDomain)); + eventPayload[5].DataPointer = ((IntPtr)(&appDomain)); if (TasksSetActivityIds) { Guid childActivityId = CreateGuidForTaskID(TaskID); WriteEventWithRelatedActivityIdCore(TASKSCHEDULED_ID, &childActivityId, 6, eventPayload); } - else + else WriteEventCore(TASKSCHEDULED_ID, 6, eventPayload); } } @@ -251,13 +251,13 @@ namespace System.Threading.Tasks /// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param> /// <param name="OriginatingTaskID">The task ID.</param> /// <param name="TaskID">The task ID.</param> - [Event(TASKSTARTED_ID, + [Event(TASKSTARTED_ID, Level = EventLevel.Informational, Keywords = Keywords.Tasks)] public void TaskStarted( int OriginatingTaskSchedulerID, int OriginatingTaskID, // PFX_COMMON_EVENT_HEADER int TaskID) { - if (IsEnabled(EventLevel.Informational, Keywords.Tasks)) + if (IsEnabled(EventLevel.Informational, Keywords.Tasks)) WriteEvent(TASKSTARTED_ID, OriginatingTaskSchedulerID, OriginatingTaskID, TaskID); } #endregion @@ -270,33 +270,33 @@ 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> - [Event(TASKCOMPLETED_ID, Version=1, + [Event(TASKCOMPLETED_ID, Version = 1, Level = EventLevel.Informational, Keywords = Keywords.TaskStops)] public void TaskCompleted( int OriginatingTaskSchedulerID, int OriginatingTaskID, // PFX_COMMON_EVENT_HEADER int TaskID, bool IsExceptional) { - if (IsEnabled(EventLevel.Informational, Keywords.Tasks)) + if (IsEnabled(EventLevel.Informational, Keywords.Tasks)) { unsafe { EventData* eventPayload = stackalloc EventData[4]; Int32 isExceptionalInt = IsExceptional ? 1 : 0; eventPayload[0].Size = sizeof(int); - eventPayload[0].DataPointer = ((IntPtr) (&OriginatingTaskSchedulerID)); + eventPayload[0].DataPointer = ((IntPtr)(&OriginatingTaskSchedulerID)); eventPayload[1].Size = sizeof(int); - eventPayload[1].DataPointer = ((IntPtr) (&OriginatingTaskID)); + eventPayload[1].DataPointer = ((IntPtr)(&OriginatingTaskID)); eventPayload[2].Size = sizeof(int); - eventPayload[2].DataPointer = ((IntPtr) (&TaskID)); + eventPayload[2].DataPointer = ((IntPtr)(&TaskID)); eventPayload[3].Size = sizeof(int); - eventPayload[3].DataPointer = ((IntPtr) (&isExceptionalInt)); + eventPayload[3].DataPointer = ((IntPtr)(&isExceptionalInt)); WriteEventCore(TASKCOMPLETED_ID, 4, eventPayload); } - } + } } #endregion - #region TaskWaitBegin + #region TaskWaitBegin /// <summary> /// Fired when starting to wait for a taks's completion explicitly or implicitly. /// </summary> @@ -307,13 +307,13 @@ 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> - [Event(TASKWAITBEGIN_ID, Version=3, Task = TplEtwProvider.Tasks.TaskWait, Opcode = EventOpcode.Send, - Level = EventLevel.Informational, Keywords = Keywords.TaskTransfer|Keywords.Tasks)] + [Event(TASKWAITBEGIN_ID, Version = 3, Task = TplEtwProvider.Tasks.TaskWait, Opcode = EventOpcode.Send, + Level = EventLevel.Informational, Keywords = Keywords.TaskTransfer | Keywords.Tasks)] public void TaskWaitBegin( int OriginatingTaskSchedulerID, int OriginatingTaskID, // PFX_COMMON_EVENT_HEADER int TaskID, TaskWaitBehavior Behavior, int ContinueWithTaskID) { - if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.TaskTransfer|Keywords.Tasks)) + if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.TaskTransfer | Keywords.Tasks)) { unsafe { @@ -348,7 +348,7 @@ namespace System.Threading.Tasks /// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param> /// <param name="OriginatingTaskID">The task ID.</param> /// <param name="TaskID">The task ID.</param> - [Event(TASKWAITEND_ID, + [Event(TASKWAITEND_ID, Level = EventLevel.Verbose, Keywords = Keywords.Tasks)] public void TaskWaitEnd( int OriginatingTaskSchedulerID, int OriginatingTaskID, // PFX_COMMON_EVENT_HEADER @@ -395,23 +395,23 @@ 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> - [Event(AWAITTASKCONTINUATIONSCHEDULED_ID, Task = Tasks.AwaitTaskContinuationScheduled, Opcode = EventOpcode.Send, - Level = EventLevel.Informational, Keywords = Keywords.TaskTransfer|Keywords.Tasks)] + [Event(AWAITTASKCONTINUATIONSCHEDULED_ID, Task = Tasks.AwaitTaskContinuationScheduled, Opcode = EventOpcode.Send, + Level = EventLevel.Informational, Keywords = Keywords.TaskTransfer | Keywords.Tasks)] public void AwaitTaskContinuationScheduled( int OriginatingTaskSchedulerID, int OriginatingTaskID, // PFX_COMMON_EVENT_HEADER int ContinuwWithTaskId) { - if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.TaskTransfer|Keywords.Tasks)) - { + if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.TaskTransfer | Keywords.Tasks)) + { unsafe { EventData* eventPayload = stackalloc EventData[3]; eventPayload[0].Size = sizeof(int); - eventPayload[0].DataPointer = ((IntPtr) (&OriginatingTaskSchedulerID)); + eventPayload[0].DataPointer = ((IntPtr)(&OriginatingTaskSchedulerID)); eventPayload[1].Size = sizeof(int); - eventPayload[1].DataPointer = ((IntPtr) (&OriginatingTaskID)); + eventPayload[1].DataPointer = ((IntPtr)(&OriginatingTaskID)); eventPayload[2].Size = sizeof(int); - eventPayload[2].DataPointer = ((IntPtr) (&ContinuwWithTaskId)); + eventPayload[2].DataPointer = ((IntPtr)(&ContinuwWithTaskId)); if (TasksSetActivityIds) { Guid continuationActivityId = CreateGuidForTaskID(ContinuwWithTaskId); @@ -423,116 +423,116 @@ namespace System.Threading.Tasks } } - [Event(TRACEOPERATIONSTART_ID, Version=1, + [Event(TRACEOPERATIONSTART_ID, Version = 1, Level = EventLevel.Informational, Keywords = Keywords.AsyncCausalityOperation)] public void TraceOperationBegin(int TaskID, string OperationName, long RelatedContext) { - if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.AsyncCausalityOperation)) + if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.AsyncCausalityOperation)) { unsafe { - fixed(char* operationNamePtr = OperationName) + fixed (char* operationNamePtr = OperationName) { EventData* eventPayload = stackalloc EventData[3]; eventPayload[0].Size = sizeof(int); - eventPayload[0].DataPointer = ((IntPtr) (&TaskID)); + eventPayload[0].DataPointer = ((IntPtr)(&TaskID)); eventPayload[1].Size = ((OperationName.Length + 1) * 2); - eventPayload[1].DataPointer = ((IntPtr) operationNamePtr); + eventPayload[1].DataPointer = ((IntPtr)operationNamePtr); eventPayload[2].Size = sizeof(long); - eventPayload[2].DataPointer = ((IntPtr) (&RelatedContext)); + eventPayload[2].DataPointer = ((IntPtr)(&RelatedContext)); WriteEventCore(TRACEOPERATIONSTART_ID, 3, eventPayload); } } - } + } } - [Event(TRACEOPERATIONRELATION_ID, Version=1, + [Event(TRACEOPERATIONRELATION_ID, Version = 1, Level = EventLevel.Informational, Keywords = Keywords.AsyncCausalityRelation)] public void TraceOperationRelation(int TaskID, CausalityRelation Relation) { - if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.AsyncCausalityRelation)) - WriteEvent(TRACEOPERATIONRELATION_ID, TaskID,(int) Relation); // optmized overload for this exists + if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.AsyncCausalityRelation)) + WriteEvent(TRACEOPERATIONRELATION_ID, TaskID, (int)Relation); // optmized overload for this exists } - [Event(TRACEOPERATIONSTOP_ID, Version=1, + [Event(TRACEOPERATIONSTOP_ID, Version = 1, Level = EventLevel.Informational, Keywords = Keywords.AsyncCausalityOperation)] public void TraceOperationEnd(int TaskID, AsyncCausalityStatus Status) { - if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.AsyncCausalityOperation)) - WriteEvent(TRACEOPERATIONSTOP_ID, TaskID,(int) Status); // optmized overload for this exists + if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.AsyncCausalityOperation)) + WriteEvent(TRACEOPERATIONSTOP_ID, TaskID, (int)Status); // optmized overload for this exists } - [Event(TRACESYNCHRONOUSWORKSTART_ID, Version=1, + [Event(TRACESYNCHRONOUSWORKSTART_ID, Version = 1, Level = EventLevel.Informational, Keywords = Keywords.AsyncCausalitySynchronousWork)] public void TraceSynchronousWorkBegin(int TaskID, CausalitySynchronousWork Work) { - if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.AsyncCausalitySynchronousWork)) - WriteEvent(TRACESYNCHRONOUSWORKSTART_ID, TaskID,(int) Work); // optmized overload for this exists + if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.AsyncCausalitySynchronousWork)) + WriteEvent(TRACESYNCHRONOUSWORKSTART_ID, TaskID, (int)Work); // optmized overload for this exists } - [Event(TRACESYNCHRONOUSWORKSTOP_ID, Version=1, + [Event(TRACESYNCHRONOUSWORKSTOP_ID, Version = 1, Level = EventLevel.Informational, Keywords = Keywords.AsyncCausalitySynchronousWork)] public void TraceSynchronousWorkEnd(CausalitySynchronousWork Work) { - if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.AsyncCausalitySynchronousWork)) + if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.AsyncCausalitySynchronousWork)) { unsafe { EventData* eventPayload = stackalloc EventData[1]; eventPayload[0].Size = sizeof(int); - eventPayload[0].DataPointer = ((IntPtr) (&Work)); + eventPayload[0].DataPointer = ((IntPtr)(&Work)); WriteEventCore(TRACESYNCHRONOUSWORKSTOP_ID, 1, eventPayload); } - } + } } [NonEvent] - unsafe public void RunningContinuation(int TaskID, object Object) { RunningContinuation(TaskID, (long) *((void**) JitHelpers.UnsafeCastToStackPointer(ref Object))); } + unsafe public void RunningContinuation(int TaskID, object Object) { RunningContinuation(TaskID, (long)*((void**)JitHelpers.UnsafeCastToStackPointer(ref Object))); } [Event(20, Keywords = Keywords.Debug)] - private void RunningContinuation(int TaskID, long Object) - { + private void RunningContinuation(int TaskID, long Object) + { if (Debug) - WriteEvent(20, TaskID, Object); + WriteEvent(20, TaskID, Object); } [NonEvent] - unsafe public void RunningContinuationList(int TaskID, int Index, object Object) { RunningContinuationList(TaskID, Index, (long) *((void**) JitHelpers.UnsafeCastToStackPointer(ref Object))); } + unsafe public void RunningContinuationList(int TaskID, int Index, object Object) { RunningContinuationList(TaskID, Index, (long)*((void**)JitHelpers.UnsafeCastToStackPointer(ref Object))); } [Event(21, Keywords = Keywords.Debug)] - public void RunningContinuationList(int TaskID, int Index, long Object) - { + public void RunningContinuationList(int TaskID, int Index, long Object) + { if (Debug) - WriteEvent(21, TaskID, Index, Object); - } + WriteEvent(21, TaskID, Index, Object); + } [Event(23, Keywords = Keywords.Debug)] - public void DebugFacilityMessage(string Facility, string Message) { WriteEvent(23, Facility, Message); } + public void DebugFacilityMessage(string Facility, string Message) { WriteEvent(23, Facility, Message); } [Event(24, Keywords = Keywords.Debug)] - public void DebugFacilityMessage1(string Facility, string Message, string Value1) { WriteEvent(24, Facility, Message, Value1); } + public void DebugFacilityMessage1(string Facility, string Message, string Value1) { WriteEvent(24, Facility, Message, Value1); } [Event(25, Keywords = Keywords.DebugActivityId)] public void SetActivityId(Guid NewId) { if (DebugActivityId) - WriteEvent(25, NewId); - } + WriteEvent(25, NewId); + } [Event(26, Keywords = Keywords.Debug)] - public void NewID(int TaskID) - { + public void NewID(int TaskID) + { if (Debug) - WriteEvent(26, TaskID); - } + WriteEvent(26, TaskID); + } /// <summary> /// Activity IDs are GUIDS but task IDS are integers (and are not unique across appdomains /// This routine creates a process wide unique GUID given a task ID /// </summary> - internal static Guid CreateGuidForTaskID(int taskID) + internal static Guid CreateGuidForTaskID(int taskID) { // The thread pool generated a process wide unique GUID from a task GUID by // using the taskGuid, the appdomain ID, and 8 bytes of 'randomization' chosen by @@ -540,9 +540,9 @@ namespace System.Threading.Tasks // These were generated by CreateGuid, and are reasonably random (and thus unlikley to collide uint pid = EventSource.s_currentPid; int appDomainID = System.Threading.Thread.GetDomainID(); - return new Guid(taskID, - (short) appDomainID , (short) (appDomainID >> 16), - (byte)pid, (byte)(pid >> 8), (byte)(pid >> 16), (byte)(pid >> 24), + return new Guid(taskID, + (short)appDomainID, (short)(appDomainID >> 16), + (byte)pid, (byte)(pid >> 8), (byte)(pid >> 16), (byte)(pid >> 24), 0xff, 0xdc, 0xd7, 0xb5); } } diff --git a/src/mscorlib/src/System/Threading/Tasks/Task.cs b/src/mscorlib/src/System/Threading/Tasks/Task.cs index c7de16c145..b9f58c0ea0 100644 --- a/src/mscorlib/src/System/Threading/Tasks/Task.cs +++ b/src/mscorlib/src/System/Threading/Tasks/Task.cs @@ -29,7 +29,6 @@ using System.Diagnostics.Tracing; namespace System.Threading.Tasks { - /// <summary> /// Utility class for allocating structs as heap variables /// </summary> @@ -41,7 +40,6 @@ namespace System.Threading.Tasks { this.Value = value; } - } /// <summary> @@ -271,7 +269,7 @@ namespace System.Threading.Tasks // but haven't yet been waited on by the parent, lazily initialized. internal volatile List<Task> m_exceptionalChildren; // A task's parent, or null if parent-less. Only set during Task construction. - internal Task m_parent; + internal Task m_parent; /// <summary> /// Sets the internal completion event. @@ -569,8 +567,8 @@ namespace System.Threading.Tasks #if DEBUG // Check the validity of internalOptions - int illegalInternalOptions = - (int) (internalOptions & + int illegalInternalOptions = + (int)(internalOptions & ~(InternalTaskOptions.PromiseTask | InternalTaskOptions.ContinuationTask | InternalTaskOptions.LazyCancellation | @@ -1785,7 +1783,7 @@ namespace System.Threading.Tasks catch (ThreadAbortException tae) { AddException(tae); - FinishThreadAbortedTask(delegateRan:false); + FinishThreadAbortedTask(delegateRan: false); } catch (Exception e) { @@ -2253,7 +2251,6 @@ namespace System.Threading.Tasks tmp.Add(childTask); } } - } if (Interlocked.Decrement(ref props.m_completionCountdown) == 0) @@ -2352,7 +2349,7 @@ namespace System.Threading.Tasks if (!IsCompleted) { HandleException(tae); - FinishThreadAbortedTask(delegateRan:false); + FinishThreadAbortedTask(delegateRan: false); } } @@ -2479,7 +2476,7 @@ namespace System.Threading.Tasks finally { currentTaskSlot = previousTask; - + // ETW event for Task Completed if (etwIsEnabled) { @@ -2992,7 +2989,6 @@ namespace System.Threading.Tasks { Thread.SpinWait(PlatformHelper.ProcessorCount * (4 << i)); } - } return IsCompleted; @@ -3050,12 +3046,10 @@ namespace System.Threading.Tasks // So we need to remeber whether we actually did the flip, so we can do clean up (finish continuations etc) mustCleanup = AtomicStateUpdate(TASK_STATE_CANCELED, TASK_STATE_DELEGATE_INVOKED | TASK_STATE_CANCELED); - // PS: This is slightly different from the regular cancellation codepath // since we record the cancellation request *after* doing the state transition. // However that shouldn't matter too much because the task was never invoked, thus can't have children } - } if (!bCancelNonExecutingOnly || bPopSucceeded || mustCleanup) @@ -3144,7 +3138,7 @@ namespace System.Threading.Tasks oce = edi.SourceException as OperationCanceledException; Debug.Assert(oce != null, "Expected EDI to contain an OCE"); } - Debug.Assert(oce.CancellationToken == tokenToRecord, + Debug.Assert(oce.CancellationToken == tokenToRecord, "Expected OCE's token to match the provided token."); #endif AddException(cancellationException, representsCancellation: true); @@ -4169,7 +4163,7 @@ namespace System.Threading.Tasks TaskContinuationOptions.LongRunning | TaskContinuationOptions.DenyChildAttach | TaskContinuationOptions.HideScheduler | - TaskContinuationOptions.AttachedToParent| + TaskContinuationOptions.AttachedToParent | TaskContinuationOptions.RunContinuationsAsynchronously; // Check that LongRunning and ExecuteSynchronously are not specified together @@ -4181,7 +4175,7 @@ namespace System.Threading.Tasks // Check that no illegal options were specified if ((continuationOptions & - ~(CreationOptionsMask | NotOnAnything | + ~(CreationOptionsMask | NotOnAnything | TaskContinuationOptions.LazyCancellation | TaskContinuationOptions.ExecuteSynchronously)) != 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.continuationOptions); @@ -4434,7 +4428,6 @@ namespace System.Threading.Tasks { // null out that TaskContinuation entry, which will be interpreted as "to be cleaned up" continuationsLocalListRef[index] = null; - } } } @@ -4517,7 +4510,6 @@ namespace System.Threading.Tasks } return WaitAll(tasks, (int)totalMilliseconds); - } /// <summary> @@ -5120,7 +5112,7 @@ namespace System.Threading.Tasks Debug.Assert(succeeded, "This should always succeed on a new task."); return task; } - + /// <summary>Creates a <see cref="Task"/> that's completed due to cancellation with the specified token.</summary> /// <param name="cancellationToken">The token with which to complete the task.</param> /// <returns>The canceled task.</returns> @@ -5129,7 +5121,7 @@ namespace System.Threading.Tasks { return FromCanceled(cancellationToken); } - + /// <summary>Creates a <see cref="Task{TResult}"/> that's completed due to cancellation with the specified token.</summary> /// <typeparam name="TResult">The type of the result returned by the task.</typeparam> /// <param name="cancellationToken">The token with which to complete the task.</param> @@ -5139,7 +5131,7 @@ namespace System.Threading.Tasks { return FromCanceled<TResult>(cancellationToken); } - + #endregion #region Run methods @@ -6137,8 +6129,8 @@ namespace System.Threading.Tasks internal virtual Delegate[] GetDelegateContinuationsForDebugger() { //Avoid an infinite loop by making sure the continuation object is not a reference to istelf. - if (this.m_continuationObject != this) - return GetDelegatesFromContinuationObject(this.m_continuationObject); + if (m_continuationObject != this) + return GetDelegatesFromContinuationObject(m_continuationObject); else return null; } @@ -6209,11 +6201,8 @@ namespace System.Threading.Tasks private static Task[] GetActiveTasks() { - return new List<Task>(s_currentActiveTasks.Values).ToArray(); } - - } internal sealed class CompletionActionInvoker : IThreadPoolWorkItem @@ -6732,5 +6721,4 @@ namespace System.Threading.Tasks public bool InvokeMayRunArbitraryCode { get { return true; } } } - } diff --git a/src/mscorlib/src/System/Threading/Tasks/TaskCanceledException.cs b/src/mscorlib/src/System/Threading/Tasks/TaskCanceledException.cs index f15e3e783a..890a9c8b9b 100644 --- a/src/mscorlib/src/System/Threading/Tasks/TaskCanceledException.cs +++ b/src/mscorlib/src/System/Threading/Tasks/TaskCanceledException.cs @@ -16,14 +16,12 @@ using System.Runtime.Serialization; namespace System.Threading.Tasks { - /// <summary> /// Represents an exception used to communicate task cancellation. /// </summary> [Serializable] public class TaskCanceledException : OperationCanceledException { - [NonSerialized] private Task m_canceledTask; // The task which has been canceled. @@ -60,7 +58,7 @@ namespace System.Threading.Tasks /// </summary> /// <param name="task">A task that has been canceled.</param> public TaskCanceledException(Task task) : - base(Environment.GetResourceString("TaskCanceledException_ctor_DefaultMessage"), task!=null ? task.CancellationToken:new CancellationToken()) + base(Environment.GetResourceString("TaskCanceledException_ctor_DefaultMessage"), task != null ? task.CancellationToken : new CancellationToken()) { m_canceledTask = task; } @@ -87,7 +85,5 @@ namespace System.Threading.Tasks { get { return m_canceledTask; } } - } - } diff --git a/src/mscorlib/src/System/Threading/Tasks/TaskCompletionSource.cs b/src/mscorlib/src/System/Threading/Tasks/TaskCompletionSource.cs index 017de0e485..0c80afd22c 100644 --- a/src/mscorlib/src/System/Threading/Tasks/TaskCompletionSource.cs +++ b/src/mscorlib/src/System/Threading/Tasks/TaskCompletionSource.cs @@ -131,7 +131,7 @@ namespace System.Threading.Tasks { // Spin wait until the completion is finalized by another thread. var sw = new SpinWait(); - while (!m_task.IsCompleted) + while (!m_task.IsCompleted) sw.SpinOnce(); } @@ -185,7 +185,7 @@ namespace System.Threading.Tasks public bool TrySetException(IEnumerable<Exception> exceptions) { if (exceptions == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.exceptions); - + List<Exception> defensiveCopy = new List<Exception>(); foreach (Exception e in exceptions) { @@ -346,7 +346,7 @@ namespace System.Threading.Tasks /// <exception cref="T:System.ObjectDisposedException">The <see cref="Task"/> was disposed.</exception> public void SetCanceled() { - if(!TrySetCanceled()) + if (!TrySetCanceled()) ThrowHelper.ThrowInvalidOperationException(ExceptionResource.TaskT_TransitionToFinal_AlreadyCompleted); } } diff --git a/src/mscorlib/src/System/Threading/Tasks/TaskContinuation.cs b/src/mscorlib/src/System/Threading/Tasks/TaskContinuation.cs index 3c6ccd8dd4..848a0ecbc2 100644 --- a/src/mscorlib/src/System/Threading/Tasks/TaskContinuation.cs +++ b/src/mscorlib/src/System/Threading/Tasks/TaskContinuation.cs @@ -32,7 +32,7 @@ namespace System.Threading.Tasks Task antecedent, Delegate action, object state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions) : base(action, state, Task.InternalCurrentIfAttached(creationOptions), default(CancellationToken), creationOptions, internalOptions, null) { - Contract.Requires(action is Action<Task> || action is Action<Task, object>, + Contract.Requires(action is Action<Task> || action is Action<Task, object>, "Invalid delegate type in ContinuationTaskFromTask"); m_antecedent = antecedent; } @@ -45,7 +45,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; - Debug.Assert(antecedent != null, + Debug.Assert(antecedent != null, "No antecedent was set for the ContinuationTaskFromTask."); m_antecedent = null; @@ -79,7 +79,7 @@ namespace System.Threading.Tasks Task antecedent, Delegate function, object state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions) : base(function, state, Task.InternalCurrentIfAttached(creationOptions), default(CancellationToken), creationOptions, internalOptions, null) { - Contract.Requires(function is Func<Task, TResult> || function is Func<Task, object, TResult>, + Contract.Requires(function is Func<Task, TResult> || function is Func<Task, object, TResult>, "Invalid delegate type in ContinuationResultTaskFromTask"); m_antecedent = antecedent; } @@ -92,7 +92,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; - Debug.Assert(antecedent != null, + Debug.Assert(antecedent != null, "No antecedent was set for the ContinuationResultTaskFromTask."); m_antecedent = null; @@ -126,7 +126,7 @@ namespace System.Threading.Tasks Task<TAntecedentResult> antecedent, Delegate action, object state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions) : base(action, state, Task.InternalCurrentIfAttached(creationOptions), default(CancellationToken), creationOptions, internalOptions, null) { - Contract.Requires(action is Action<Task<TAntecedentResult>> || action is Action<Task<TAntecedentResult>, object>, + Contract.Requires(action is Action<Task<TAntecedentResult>> || action is Action<Task<TAntecedentResult>, object>, "Invalid delegate type in ContinuationTaskFromResultTask"); m_antecedent = antecedent; } @@ -139,7 +139,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; - Debug.Assert(antecedent != null, + Debug.Assert(antecedent != null, "No antecedent was set for the ContinuationTaskFromResultTask."); m_antecedent = null; @@ -186,7 +186,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; - Debug.Assert(antecedent != null, + Debug.Assert(antecedent != null, "No antecedent was set for the ContinuationResultTaskFromResultTask."); m_antecedent = null; @@ -276,7 +276,6 @@ namespace System.Threading.Tasks } internal abstract Delegate[] GetDelegateContinuationsForDebugger(); - } /// <summary>Provides the standard implementation of a task continuation.</summary> @@ -505,7 +504,8 @@ namespace System.Threading.Tasks // Create the continuation task task. If we're allowed to inline, try to do so. // The target scheduler may still deny us from executing on this thread, in which case this'll be queued. - var task = CreateTask(state => { + var task = CreateTask(state => + { try { ((Action)state)(); } catch (Exception exc) { ThrowAsyncIfNecessary(exc); } }, m_action, m_scheduler); @@ -558,10 +558,10 @@ namespace System.Threading.Tasks Contract.Requires(scheduler != null); return new Task( - action, state, null, default(CancellationToken), - TaskCreationOptions.None, InternalTaskOptions.QueuedByRuntime, scheduler) - { - CapturedContext = m_capturedContext + action, state, null, default(CancellationToken), + TaskCreationOptions.None, InternalTaskOptions.QueuedByRuntime, scheduler) + { + CapturedContext = m_capturedContext }; } @@ -590,7 +590,7 @@ namespace System.Threading.Tasks // We couldn't inline, so now we need to schedule it ThreadPool.UnsafeQueueCustomWorkItem(this, forceGlobal: false); - } + } } /// <summary> @@ -626,7 +626,7 @@ namespace System.Threading.Tasks } /// <summary>IThreadPoolWorkItem override, which is the entry function for this when the ThreadPool scheduler decides to run it.</summary> - void ExecuteWorkItemHelper() + private void ExecuteWorkItemHelper() { var etwLog = TplEtwProvider.Log; Guid savedActivityId = Guid.Empty; @@ -645,7 +645,7 @@ namespace System.Threading.Tasks { m_action(); } - // If there is an execution context, get the cached delegate and run the action under the context. + // If there is an execution context, get the cached delegate and run the action under the context. else { ExecutionContext.Run(m_capturedContext, GetInvokeActionCallback(), m_action); @@ -815,5 +815,4 @@ namespace System.Threading.Tasks 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 ee1112a93f..2ff127d7b7 100644 --- a/src/mscorlib/src/System/Threading/Tasks/TaskExceptionHolder.cs +++ b/src/mscorlib/src/System/Threading/Tasks/TaskExceptionHolder.cs @@ -70,9 +70,9 @@ namespace System.Threading.Tasks private static void EnsureADUnloadCallbackRegistered() { - if (s_adUnloadEventHandler == null && - Interlocked.CompareExchange( ref s_adUnloadEventHandler, - AppDomainUnloadCallback, + if (s_adUnloadEventHandler == null && + Interlocked.CompareExchange(ref s_adUnloadEventHandler, + AppDomainUnloadCallback, null) == null) { AppDomain.CurrentDomain.DomainUnload += s_adUnloadEventHandler; @@ -93,7 +93,7 @@ namespace System.Threading.Tasks // We need to do this filtering because all TaskExceptionHolders will be finalized during shutdown or unload // regardles of reachability of the task (i.e. even if the user code was about to observe the task's exception), // which can otherwise lead to spurious crashes during shutdown. - if (m_faultExceptions != null && !m_isHandled && + if (m_faultExceptions != null && !m_isHandled && !Environment.HasShutdownStarted && !AppDomain.CurrentDomain.IsFinalizingForUnload() && !s_domainUnloadStarted) { // We don't want to crash the finalizer thread if any ThreadAbortExceptions @@ -124,14 +124,14 @@ namespace System.Threading.Tasks // will have been marked as handled before even getting here. // Give users a chance to keep this exception from crashing the process - + // First, publish the unobserved exception and allow users to observe it AggregateException exceptionToThrow = new AggregateException( Environment.GetResourceString("TaskExceptionHolder_UnhandledException"), m_faultExceptions); UnobservedTaskExceptionEventArgs ueea = new UnobservedTaskExceptionEventArgs(exceptionToThrow); TaskScheduler.PublishUnobservedTaskException(m_task, ueea); - + // Now, if we are still unobserved and we're configured to crash on unobserved, throw the exception. // We need to publish the event above even if we're not going to crash, hence // why this check doesn't come at the beginning of the method. @@ -164,7 +164,7 @@ namespace System.Threading.Tasks { Contract.Requires(exceptionObject != null, "TaskExceptionHolder.Add(): Expected a non-null exceptionObject"); Contract.Requires( - exceptionObject is Exception || exceptionObject is IEnumerable<Exception> || + exceptionObject is Exception || exceptionObject is IEnumerable<Exception> || exceptionObject is ExceptionDispatchInfo || exceptionObject is IEnumerable<ExceptionDispatchInfo>, "TaskExceptionHolder.Add(): Expected Exception, IEnumerable<Exception>, ExceptionDispatchInfo, or IEnumerable<ExceptionDispatchInfo>"); @@ -180,16 +180,16 @@ namespace System.Threading.Tasks private void SetCancellationException(object exceptionObject) { Contract.Requires(exceptionObject != null, "Expected exceptionObject to be non-null."); - - Debug.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. + // Breaking this assumption will overwrite a previously OCE, + // and implies something may be wrong elsewhere, since there should only ever be one. - Debug.Assert(m_faultExceptions == null, + 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. + // Breaking this assumption shouldn't hurt anything here, but it implies something may be wrong elsewhere. + // If this changes, make sure to only conditionally mark as handled below. // Store the cancellation exception var oce = exceptionObject as OperationCanceledException; @@ -267,13 +267,13 @@ namespace System.Threading.Tasks exceptions.AddRange(ediColl); #if DEBUG Debug.Assert(exceptions.Count > 0, "There should be at least one dispatch info."); - foreach(var tmp in exceptions) + foreach (var tmp in exceptions) { Debug.Assert(tmp != null, "No dispatch infos should be null"); } #endif } - // Anything else is a programming error + // Anything else is a programming error else { throw new ArgumentException(Environment.GetResourceString("TaskExceptionHolder_UnknownExceptionType"), nameof(exceptionObject)); @@ -281,7 +281,7 @@ namespace System.Threading.Tasks } } } - + // If all of the exceptions are ThreadAbortExceptions and/or // AppDomainUnloadExceptions, we do not want the finalization diff --git a/src/mscorlib/src/System/Threading/Tasks/TaskFactory.cs b/src/mscorlib/src/System/Threading/Tasks/TaskFactory.cs index ed9b798902..fd6c7216bb 100644 --- a/src/mscorlib/src/System/Threading/Tasks/TaskFactory.cs +++ b/src/mscorlib/src/System/Threading/Tasks/TaskFactory.cs @@ -2315,7 +2315,7 @@ namespace System.Threading.Tasks { Contract.Requires(tasks != null, "Expected non-null collection of tasks"); _tasks = tasks; - + if (AsyncCausalityTracer.LoggingOn) AsyncCausalityTracer.TraceOperationCreation(CausalityTraceLevel.Required, this.Id, "TaskFactory.ContinueWhenAny", 0); @@ -2358,7 +2358,6 @@ namespace System.Threading.Tasks !task.IsCompleted) task.RemoveContinuation(this); } _tasks = null; - } } @@ -2380,7 +2379,7 @@ namespace System.Threading.Tasks bool checkArgsOnly = false; int numTasks = tasks.Count; - for(int i=0; i<numTasks; i++) + for (int i = 0; i < numTasks; i++) { var task = tasks[i]; if (task == null) throw new ArgumentException(Environment.GetResourceString("Task_MultiTaskContinuation_NullTask"), nameof(tasks)); @@ -2654,7 +2653,7 @@ namespace System.Threading.Tasks if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction)); Contract.EndContractBlock(); - return TaskFactory<TResult>.ContinueWhenAnyImpl(tasks, continuationFunction, null,continuationOptions, m_defaultCancellationToken, DefaultScheduler); + return TaskFactory<TResult>.ContinueWhenAnyImpl(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler); } /// <summary> @@ -2766,7 +2765,7 @@ namespace System.Threading.Tasks if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction)); Contract.EndContractBlock(); - return TaskFactory<TResult>.ContinueWhenAnyImpl<TAntecedentResult>(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler); + return TaskFactory<TResult>.ContinueWhenAnyImpl<TAntecedentResult>(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler); } /// <summary> @@ -3080,5 +3079,4 @@ namespace System.Threading.Tasks Contract.EndContractBlock(); } } - } diff --git a/src/mscorlib/src/System/Threading/Tasks/TaskScheduler.cs b/src/mscorlib/src/System/Threading/Tasks/TaskScheduler.cs index 7cdf1964ac..94d3f1189e 100644 --- a/src/mscorlib/src/System/Threading/Tasks/TaskScheduler.cs +++ b/src/mscorlib/src/System/Threading/Tasks/TaskScheduler.cs @@ -11,6 +11,7 @@ // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // Disable the "reference to volatile field not treated as volatile" error. #pragma warning disable 0420 + using System; using System.Collections.Generic; using System.Globalization; @@ -23,7 +24,6 @@ using System.Runtime.CompilerServices; namespace System.Threading.Tasks { - /// <summary> /// Represents an abstract scheduler for tasks. /// </summary> @@ -46,7 +46,7 @@ namespace System.Threading.Tasks // // User Provided Methods and Properties // - + /// <summary> /// Queues a <see cref="T:System.Threading.Tasks.Task">Task</see> to the scheduler. /// </summary> @@ -168,7 +168,7 @@ namespace System.Threading.Tasks // // Internal overridable methods // - + /// <summary> /// Attempts to execute the target task synchronously. @@ -183,14 +183,14 @@ namespace System.Threading.Tasks // Do not inline TaskCompletionSource-style (a.k.a. "promise") tasks. // No need to attempt inlining if the task body was already run (i.e. either TASK_STATE_DELEGATE_INVOKED or TASK_STATE_CANCELED bits set) TaskScheduler ets = task.ExecutingTaskScheduler; - + // Delegate cross-scheduler inlining requests to target scheduler - if(ets != this && ets !=null) return ets.TryRunInline(task, taskWasPreviouslyQueued); + if (ets != this && ets != null) return ets.TryRunInline(task, taskWasPreviouslyQueued); StackGuard currentStackGuard; - if( (ets == null) || + if ((ets == null) || (task.m_action == null) || - task.IsDelegateInvoked || + task.IsDelegateInvoked || task.IsCanceled || (currentStackGuard = Task.CurrentStackGuard).TryBeginInliningScope() == false) { @@ -216,7 +216,7 @@ namespace System.Threading.Tasks // If the custom scheduler returned true, we should either have the TASK_STATE_DELEGATE_INVOKED or TASK_STATE_CANCELED bit set // Otherwise the scheduler is buggy - if (bInlined && !(task.IsDelegateInvoked || task.IsCanceled)) + if (bInlined && !(task.IsDelegateInvoked || task.IsCanceled)) { throw new InvalidOperationException(Environment.GetResourceString("TaskScheduler_InconsistentStateAfterTryExecuteTaskInline")); } @@ -240,7 +240,7 @@ namespace System.Threading.Tasks /// Notifies the scheduler that a work item has made progress. /// </summary> internal virtual void NotifyWorkItemProgress() - { + { } /// <summary> @@ -275,7 +275,7 @@ namespace System.Threading.Tasks // The global container that keeps track of TaskScheduler instances for debugging purposes. private static ConditionalWeakTable<TaskScheduler, object> s_activeTaskSchedulers; - + // An AppDomain-wide default manager. private static readonly TaskScheduler s_defaultTaskScheduler = new ThreadPoolTaskScheduler(); @@ -322,7 +322,7 @@ namespace System.Threading.Tasks /// <summary> /// Gets the default <see cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see> instance. /// </summary> - public static TaskScheduler Default + public static TaskScheduler Default { get { @@ -337,7 +337,7 @@ namespace System.Threading.Tasks /// <remarks> /// When not called from within a task, <see cref="Current"/> will return the <see cref="Default"/> scheduler. /// </remarks> - public static TaskScheduler Current + public static TaskScheduler Current { get { @@ -358,7 +358,7 @@ namespace System.Threading.Tasks get { Task currentTask = Task.InternalCurrent; - return ( (currentTask != null) + return ((currentTask != null) && ((currentTask.CreationOptions & TaskCreationOptions.HideScheduler) == 0) ) ? currentTask.ExecutingTaskScheduler : null; } @@ -404,7 +404,7 @@ namespace System.Threading.Tasks { newId = Interlocked.Increment(ref s_taskSchedulerIdCounter); } while (newId == 0); - + Interlocked.CompareExchange(ref m_taskSchedulerId, newId, 0); } @@ -483,12 +483,12 @@ namespace System.Threading.Tasks lock (_unobservedTaskExceptionLockObject) _unobservedTaskException -= value; } } - - + + //////////////////////////////////////////////////////////// // // Internal methods @@ -596,17 +596,16 @@ namespace System.Threading.Tasks // returns the scheduler’s Id public Int32 Id - { - get { return m_taskScheduler.Id; } + { + get { return m_taskScheduler.Id; } } // returns the scheduler’s GetScheduledTasks - public IEnumerable<Task> ScheduledTasks + public IEnumerable<Task> ScheduledTasks { get { return m_taskScheduler.GetScheduledTasks(); } } } - } @@ -636,7 +635,6 @@ namespace System.Threading.Tasks } m_synchronizationContext = synContext; - } /// <summary> @@ -725,7 +723,7 @@ namespace System.Threading.Tasks /// Gets whether this exception has been marked as "observed." /// </summary> public bool Observed { get { return m_observed; } } - + /// <summary> /// The Exception that went unobserved. /// </summary> diff --git a/src/mscorlib/src/System/Threading/Tasks/TaskSchedulerException.cs b/src/mscorlib/src/System/Threading/Tasks/TaskSchedulerException.cs index 1d85e49342..3726a5e18e 100644 --- a/src/mscorlib/src/System/Threading/Tasks/TaskSchedulerException.cs +++ b/src/mscorlib/src/System/Threading/Tasks/TaskSchedulerException.cs @@ -16,7 +16,6 @@ using System.Runtime.Serialization; namespace System.Threading.Tasks { - /// <summary> /// Represents an exception used to communicate an invalid operation by a /// <see cref="T:System.Threading.Tasks.TaskScheduler"/>. @@ -74,8 +73,5 @@ namespace System.Threading.Tasks : base(info, context) { } - - } - } diff --git a/src/mscorlib/src/System/Threading/Tasks/TaskToApm.cs b/src/mscorlib/src/System/Threading/Tasks/TaskToApm.cs index 90743aeec5..fdd62c95f5 100644 --- a/src/mscorlib/src/System/Threading/Tasks/TaskToApm.cs +++ b/src/mscorlib/src/System/Threading/Tasks/TaskToApm.cs @@ -60,7 +60,7 @@ namespace System.Threading.Tasks { // Asynchronous completion asyncResult = task.AsyncState == state ? (IAsyncResult)task : new TaskWrapperAsyncResult(task, state, completedSynchronously: false); - if (callback != null) + if (callback != null) InvokeCallbackWhenTaskCompletes(task, callback, asyncResult); } return asyncResult; @@ -129,7 +129,7 @@ namespace System.Threading.Tasks // We use OnCompleted rather than ContinueWith in order to avoid running synchronously // if the task has already completed by the time we get here. This is separated out into // its own method currently so that we only pay for the closure if necessary. - antecedent.ConfigureAwait(continueOnCapturedContext:false) + antecedent.ConfigureAwait(continueOnCapturedContext: false) .GetAwaiter() .OnCompleted(() => callback(asyncResult)); @@ -167,7 +167,7 @@ namespace System.Threading.Tasks /// <param name="task">The Task to wrap.</param> /// <param name="state">The new AsyncState value</param> /// <param name="completedSynchronously">The new CompletedSynchronously value.</param> - internal TaskWrapperAsyncResult(Task task, object state, bool completedSynchronously) + internal TaskWrapperAsyncResult(Task task, object state, bool completedSynchronously) { Contract.Requires(task != null); Contract.Requires(!completedSynchronously || task.IsCompleted, "If completedSynchronously is true, the task must be completed."); diff --git a/src/mscorlib/src/System/Threading/Tasks/ThreadPoolTaskScheduler.cs b/src/mscorlib/src/System/Threading/Tasks/ThreadPoolTaskScheduler.cs index a1852f8bfb..e69a89fe66 100644 --- a/src/mscorlib/src/System/Threading/Tasks/ThreadPoolTaskScheduler.cs +++ b/src/mscorlib/src/System/Threading/Tasks/ThreadPoolTaskScheduler.cs @@ -23,7 +23,7 @@ namespace System.Threading.Tasks /// <summary> /// An implementation of TaskScheduler that uses the ThreadPool scheduler /// </summary> - internal sealed class ThreadPoolTaskScheduler: TaskScheduler + internal sealed class ThreadPoolTaskScheduler : TaskScheduler { /// <summary> /// Constructs a new ThreadPool task scheduler object @@ -56,7 +56,7 @@ namespace System.Threading.Tasks ThreadPool.UnsafeQueueCustomWorkItem(task, forceToGlobalQueue); } } - + /// <summary> /// This internal function will do this: /// (1) If the task had previously been queued, attempt to pop it and return false if that fails. diff --git a/src/mscorlib/src/System/Threading/Tasks/future.cs b/src/mscorlib/src/System/Threading/Tasks/future.cs index 9fed97e629..147456af5f 100644 --- a/src/mscorlib/src/System/Threading/Tasks/future.cs +++ b/src/mscorlib/src/System/Threading/Tasks/future.cs @@ -82,20 +82,20 @@ namespace System.Threading.Tasks internal static readonly Func<Task<Task>, Task<TResult>> TaskWhenAnyCast = completed => (Task<TResult>)completed.Result; // Construct a promise-style task without any options. - internal Task() : + internal Task() : base() { } // Construct a promise-style task with state and options. internal Task(object state, TaskCreationOptions options) : - base(state, options, promiseStyle:true) + base(state, options, promiseStyle: true) { } // Construct a pre-completed Task<TResult> - internal Task(TResult result) : + internal Task(TResult result) : base(false, TaskCreationOptions.None, default(CancellationToken)) { m_result = result; @@ -372,9 +372,9 @@ namespace System.Threading.Tasks // Debugger support private string DebuggerDisplayResultDescription { - get + get { - return IsRanToCompletion ? "" + m_result : Environment.GetResourceString("TaskT_DebuggerNoResult"); + return IsRanToCompletion ? "" + m_result : Environment.GetResourceString("TaskT_DebuggerNoResult"); } } @@ -441,7 +441,7 @@ namespace System.Threading.Tasks bool success = TrySetResult(result); // Nobody else has had a chance to complete this Task yet, so we should succeed. - Debug.Assert(success); + Debug.Assert(success); } else { @@ -477,7 +477,7 @@ namespace System.Threading.Tasks { Debug.Assert(!IsWaitNotificationEnabledOrNotRanToCompletion, "Should only be used when the task completed successfully and there's no wait notification enabled"); - return m_result; + return m_result; } } @@ -539,7 +539,6 @@ namespace System.Threading.Tasks } return returnValue; - } // internal helper function breaks out logic used by TaskCompletionSource and AsyncMethodBuilder @@ -879,7 +878,7 @@ namespace System.Threading.Tasks /// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see> /// has already been disposed. /// </exception> - public Task ContinueWith(Action<Task<TResult>, Object> continuationAction, Object state,CancellationToken cancellationToken) + public Task ContinueWith(Action<Task<TResult>, Object> continuationAction, Object state, CancellationToken cancellationToken) { return ContinueWith(continuationAction, state, TaskScheduler.Current, cancellationToken, TaskContinuationOptions.None); } @@ -942,7 +941,7 @@ namespace System.Threading.Tasks /// The <paramref name="continuationOptions"/> argument specifies an invalid value for <see /// cref="T:System.Threading.Tasks.TaskContinuationOptions">TaskContinuationOptions</see>. /// </exception> - public Task ContinueWith(Action<Task<TResult>, Object> continuationAction, Object state,TaskContinuationOptions continuationOptions) + public Task ContinueWith(Action<Task<TResult>, Object> continuationAction, Object state, TaskContinuationOptions continuationOptions) { return ContinueWith(continuationAction, state, TaskScheduler.Current, default(CancellationToken), continuationOptions); } @@ -1014,7 +1013,7 @@ namespace System.Threading.Tasks out internalOptions); Task continuationTask = new ContinuationTaskFromResultTask<TResult>( - this, continuationAction, state, + this, continuationAction, state, creationOptions, internalOptions ); @@ -1229,7 +1228,7 @@ namespace System.Threading.Tasks out creationOptions, out internalOptions); - Task<TNewResult> continuationFuture = new ContinuationResultTaskFromResultTask<TResult,TNewResult>( + Task<TNewResult> continuationFuture = new ContinuationResultTaskFromResultTask<TResult, TNewResult>( this, continuationFunction, null, creationOptions, internalOptions ); @@ -1452,7 +1451,7 @@ namespace System.Threading.Tasks out creationOptions, out internalOptions); - Task<TNewResult> continuationFuture = new ContinuationResultTaskFromResultTask<TResult,TNewResult>( + Task<TNewResult> continuationFuture = new ContinuationResultTaskFromResultTask<TResult, TNewResult>( this, continuationFunction, state, creationOptions, internalOptions ); @@ -1467,7 +1466,7 @@ namespace System.Threading.Tasks #endregion #endregion - + /// <summary> /// Subscribes an <see cref="IObserver{TResult}"/> to receive notification of the final state of this <see cref="Task{TResult}"/>. /// </summary> @@ -1553,7 +1552,5 @@ namespace System.Threading.Tasks public int Id { get { return m_task.Id; } } public bool CancellationPending { get { return (m_task.Status == TaskStatus.WaitingToRun) && m_task.CancellationToken.IsCancellationRequested; } } public TaskStatus Status { get { return m_task.Status; } } - - } } diff --git a/src/mscorlib/src/System/Threading/Thread.cs b/src/mscorlib/src/System/Threading/Thread.cs index 60b3378e5e..0b6c1668f2 100644 --- a/src/mscorlib/src/System/Threading/Thread.cs +++ b/src/mscorlib/src/System/Threading/Thread.cs @@ -14,7 +14,8 @@ using Internal.Runtime.Augments; -namespace System.Threading { +namespace System.Threading +{ using System.Threading; using System.Runtime; using System.Runtime.InteropServices; @@ -33,9 +34,9 @@ namespace System.Threading { internal class ThreadHelper { - Delegate _start; - Object _startArg = null; - ExecutionContext _executionContext = null; + private Delegate _start; + private Object _startArg = null; + private ExecutionContext _executionContext = null; internal ThreadHelper(Delegate start) { _start = start; @@ -47,7 +48,7 @@ namespace System.Threading { } static internal ContextCallback _ccb = new ContextCallback(ThreadStart_Context); - + static private void ThreadStart_Context(Object state) { ThreadHelper t = (ThreadHelper)state; @@ -63,9 +64,9 @@ namespace System.Threading { // call back helper internal void ThreadStart(object obj) - { + { _startArg = obj; - if (_executionContext != null) + if (_executionContext != null) { ExecutionContext.Run(_executionContext, _ccb, (Object)this); } @@ -78,7 +79,7 @@ namespace System.Threading { // call back helper internal void ThreadStart() { - if (_executionContext != null) + if (_executionContext != null) { ExecutionContext.Run(_executionContext, _ccb, (Object)this); } @@ -109,10 +110,10 @@ namespace System.Threading { private ExecutionContext m_ExecutionContext; // this call context follows the logical thread private SynchronizationContext m_SynchronizationContext; // On CoreCLR, this is maintained separately from ExecutionContext - private String m_Name; - private Delegate m_Delegate; // Delegate + private String m_Name; + private Delegate m_Delegate; // Delegate - private Object m_ThreadStartArg; + private Object m_ThreadStartArg; /*========================================================================= ** The base implementation of Thread is all native. The following fields @@ -124,10 +125,10 @@ namespace System.Threading { #pragma warning disable 414 // These fields are not used from managed. // IntPtrs need to be together, and before ints, because IntPtrs are 64-bit // fields on 64-bit platforms, where they will be sorted together. - - private IntPtr DONT_USE_InternalThread; // Pointer - private int m_Priority; // INT32 - private int m_ManagedThreadId; // INT32 + + private IntPtr DONT_USE_InternalThread; // Pointer + private int m_Priority; // INT32 + private int m_ManagedThreadId; // INT32 #pragma warning restore 414 #pragma warning restore 169 @@ -141,25 +142,25 @@ namespace System.Threading { // with native code // See code:#threadCultureInfo [ThreadStatic] - internal static CultureInfo m_CurrentCulture; + internal static CultureInfo m_CurrentCulture; [ThreadStatic] - internal static CultureInfo m_CurrentUICulture; + internal static CultureInfo m_CurrentUICulture; - static AsyncLocal<CultureInfo> s_asyncLocalCurrentCulture; - static AsyncLocal<CultureInfo> s_asyncLocalCurrentUICulture; + private static AsyncLocal<CultureInfo> s_asyncLocalCurrentCulture; + private static AsyncLocal<CultureInfo> s_asyncLocalCurrentUICulture; - static void AsyncLocalSetCurrentCulture(AsyncLocalValueChangedArgs<CultureInfo> args) + private static void AsyncLocalSetCurrentCulture(AsyncLocalValueChangedArgs<CultureInfo> args) { m_CurrentCulture = args.CurrentValue; } - static void AsyncLocalSetCurrentUICulture(AsyncLocalValueChangedArgs<CultureInfo> args) + private static void AsyncLocalSetCurrentUICulture(AsyncLocalValueChangedArgs<CultureInfo> args) { m_CurrentUICulture = args.CurrentValue; } // Adding an empty default ctor for annotation purposes - internal Thread(){} + internal Thread() { } /*========================================================================= ** Creates a new Thread object which will begin execution at @@ -167,37 +168,45 @@ namespace System.Threading { ** ** Exceptions: ArgumentNullException if start == null. =========================================================================*/ - public Thread(ThreadStart start) { - if (start == null) { + public Thread(ThreadStart start) + { + if (start == null) + { throw new ArgumentNullException(nameof(start)); } Contract.EndContractBlock(); - SetStartHelper((Delegate)start,0); //0 will setup Thread with default stackSize + SetStartHelper((Delegate)start, 0); //0 will setup Thread with default stackSize } - internal Thread(ThreadStart start, int maxStackSize) { - if (start == null) { + internal Thread(ThreadStart start, int maxStackSize) + { + if (start == null) + { throw new ArgumentNullException(nameof(start)); } if (0 > maxStackSize) - throw new ArgumentOutOfRangeException(nameof(maxStackSize),Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); + throw new ArgumentOutOfRangeException(nameof(maxStackSize), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); SetStartHelper((Delegate)start, maxStackSize); } - public Thread(ParameterizedThreadStart start) { - if (start == null) { + public Thread(ParameterizedThreadStart start) + { + if (start == null) + { throw new ArgumentNullException(nameof(start)); } Contract.EndContractBlock(); SetStartHelper((Delegate)start, 0); } - internal Thread(ParameterizedThreadStart start, int maxStackSize) { - if (start == null) { + internal Thread(ParameterizedThreadStart start, int maxStackSize) + { + if (start == null) + { throw new ArgumentNullException(nameof(start)); } if (0 > maxStackSize) - throw new ArgumentOutOfRangeException(nameof(maxStackSize),Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); + throw new ArgumentOutOfRangeException(nameof(maxStackSize), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); SetStartHelper((Delegate)start, maxStackSize); } @@ -247,7 +256,7 @@ namespace System.Threading { { //In the case of a null delegate (second call to start on same thread) // StartInternal method will take care of the error reporting - if(m_Delegate is ThreadStart) + if (m_Delegate is ThreadStart) { //We expect the thread to be setup with a ParameterizedThreadStart // if this constructor is called. @@ -283,7 +292,7 @@ namespace System.Threading { internal ExecutionContext ExecutionContext { - get { return m_ExecutionContext; } + get { return m_ExecutionContext; } set { m_ExecutionContext = value; } } @@ -318,14 +327,14 @@ namespace System.Threading { { SleepInternal(millisecondsTimeout); // Ensure we don't return to app code when the pause is underway - if(AppDomainPauseManager.IsPaused) + if (AppDomainPauseManager.IsPaused) AppDomainPauseManager.ResumeEvent.WaitOneWithoutFAS(); } public static void Sleep(TimeSpan timeout) { long tm = (long)timeout.TotalMilliseconds; - if (tm < -1 || tm > (long) Int32.MaxValue) + if (tm < -1 || tm > (long)Int32.MaxValue) throw new ArgumentOutOfRangeException(nameof(timeout), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); Sleep((int)tm); } @@ -351,9 +360,11 @@ namespace System.Threading { { return YieldInternal(); } - - public static new Thread CurrentThread { - get { + + public static new Thread CurrentThread + { + get + { Contract.Ensures(Contract.Result<Thread>() != null); return GetCurrentThreadNative(); } @@ -366,14 +377,14 @@ namespace System.Threading { Debug.Assert(maxStackSize >= 0); ThreadHelper threadStartCallBack = new ThreadHelper(start); - if(start is ThreadStart) + if (start is ThreadStart) { SetStart(new ThreadStart(threadStartCallBack.ThreadStart), maxStackSize); } else { SetStart(new ParameterizedThreadStart(threadStartCallBack.ThreadStart), maxStackSize); - } + } } /*========================================================================= @@ -435,22 +446,27 @@ namespace System.Threading { // app domain get unloaded there is a code to clean up the culture from the thread // using the code in AppDomain::ReleaseDomainStores. - public CultureInfo CurrentUICulture { - get { + public CultureInfo CurrentUICulture + { + get + { Contract.Ensures(Contract.Result<CultureInfo>() != null); #if FEATURE_APPX && !FEATURE_COREFX_GLOBALIZATION - if(AppDomain.IsAppXModel()) { + if (AppDomain.IsAppXModel()) + { return CultureInfo.GetCultureInfoForUserPreferredLanguageInAppX() ?? GetCurrentUICultureNoAppX(); - } - else + } + else #endif { return GetCurrentUICultureNoAppX(); } } - set { - if (value == null) { + set + { + if (value == null) + { throw new ArgumentNullException(nameof(value)); } Contract.EndContractBlock(); @@ -482,8 +498,8 @@ namespace System.Threading { } } - internal CultureInfo GetCurrentUICultureNoAppX() { - + internal CultureInfo GetCurrentUICultureNoAppX() + { Contract.Ensures(Contract.Result<CultureInfo>() != null); #if FEATURE_COREFX_GLOBALIZATION @@ -492,7 +508,8 @@ namespace System.Threading { // Fetch a local copy of m_CurrentUICulture to // avoid race conditions that malicious user can introduce - if (m_CurrentUICulture == null) { + if (m_CurrentUICulture == null) + { CultureInfo appDomainDefaultUICulture = CultureInfo.DefaultThreadCurrentUICulture; return (appDomainDefaultUICulture != null ? appDomainDefaultUICulture : CultureInfo.UserDefaultUICulture); } @@ -515,23 +532,28 @@ namespace System.Threading { // app domain get unloaded there is a code to clean up the culture from the thread // using the code in AppDomain::ReleaseDomainStores. - public CultureInfo CurrentCulture { - get { + public CultureInfo CurrentCulture + { + get + { Contract.Ensures(Contract.Result<CultureInfo>() != null); #if FEATURE_APPX && !FEATURE_COREFX_GLOBALIZATION - if(AppDomain.IsAppXModel()) { + if (AppDomain.IsAppXModel()) + { return CultureInfo.GetCultureInfoForUserPreferredLanguageInAppX() ?? GetCurrentCultureNoAppX(); - } - else + } + else #endif { return GetCurrentCultureNoAppX(); } } - set { - if (null==value) { + set + { + if (null == value) + { throw new ArgumentNullException(nameof(value)); } Contract.EndContractBlock(); @@ -558,8 +580,8 @@ namespace System.Threading { } } - private CultureInfo GetCurrentCultureNoAppX() { - + private CultureInfo GetCurrentCultureNoAppX() + { #if FEATURE_COREFX_GLOBALIZATION return CultureInfo.CurrentCulture; #else @@ -567,8 +589,9 @@ namespace System.Threading { // Fetch a local copy of m_CurrentCulture to // avoid race conditions that malicious user can introduce - if (m_CurrentCulture == null) { - CultureInfo appDomainDefaultCulture = CultureInfo.DefaultThreadCurrentCulture; + if (m_CurrentCulture == null) + { + CultureInfo appDomainDefaultCulture = CultureInfo.DefaultThreadCurrentCulture; return (appDomainDefaultCulture != null ? appDomainDefaultCulture : CultureInfo.UserDefaultCulture); } @@ -614,12 +637,16 @@ namespace System.Threading { // Retrieves the name of the thread. // - public new String Name { - get { + public new String Name + { + get + { return m_Name; } - set { - lock(this) { + set + { + lock (this) + { if (m_Name != null) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_WriteOnce")); m_Name = value; @@ -635,7 +662,6 @@ namespace System.Threading { [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern void MemoryBarrier(); - } // End of class Thread // declaring a local var of this enum type and passing it by ref into a function that needs to do a @@ -649,5 +675,4 @@ namespace System.Threading { LookForMyCallersCaller = 2, LookForThread = 3 } - } diff --git a/src/mscorlib/src/System/Threading/ThreadAbortException.cs b/src/mscorlib/src/System/Threading/ThreadAbortException.cs index 25925048bf..21abb413db 100644 --- a/src/mscorlib/src/System/Threading/ThreadAbortException.cs +++ b/src/mscorlib/src/System/Threading/ThreadAbortException.cs @@ -15,24 +15,24 @@ ** =============================================================================*/ -namespace System.Threading -{ - using System; - using System.Runtime.Serialization; - using System.Runtime.CompilerServices; +using System; +using System.Runtime.Serialization; +using System.Runtime.CompilerServices; +namespace System.Threading +{ [Serializable] - public sealed class ThreadAbortException : SystemException + public sealed class ThreadAbortException : SystemException { - private ThreadAbortException() + private ThreadAbortException() : base(GetMessageFromNativeResources(ExceptionMessageKind.ThreadAbort)) { SetErrorCode(__HResults.COR_E_THREADABORTED); } //required for serialization - internal ThreadAbortException(SerializationInfo info, StreamingContext context) - : base(info, context) + internal ThreadAbortException(SerializationInfo info, StreamingContext context) + : base(info, context) { } } diff --git a/src/mscorlib/src/System/Threading/ThreadInterruptedException.cs b/src/mscorlib/src/System/Threading/ThreadInterruptedException.cs index 71c09649e2..2a0772d01f 100644 --- a/src/mscorlib/src/System/Threading/ThreadInterruptedException.cs +++ b/src/mscorlib/src/System/Threading/ThreadInterruptedException.cs @@ -12,29 +12,36 @@ ** ** =============================================================================*/ -namespace System.Threading { - using System.Threading; - using System; - using System.Runtime.Serialization; +using System.Threading; +using System; +using System.Runtime.Serialization; + +namespace System.Threading +{ [Serializable] - public class ThreadInterruptedException : SystemException { - public ThreadInterruptedException() - : base(GetMessageFromNativeResources(ExceptionMessageKind.ThreadInterrupted)) { + public class ThreadInterruptedException : SystemException + { + public ThreadInterruptedException() + : base(GetMessageFromNativeResources(ExceptionMessageKind.ThreadInterrupted)) + { SetErrorCode(__HResults.COR_E_THREADINTERRUPTED); } - - public ThreadInterruptedException(String message) - : base(message) { + + public ThreadInterruptedException(String message) + : base(message) + { SetErrorCode(__HResults.COR_E_THREADINTERRUPTED); } - - public ThreadInterruptedException(String message, Exception innerException) - : base(message, innerException) { + + public ThreadInterruptedException(String message, Exception innerException) + : base(message, innerException) + { SetErrorCode(__HResults.COR_E_THREADINTERRUPTED); } - protected ThreadInterruptedException(SerializationInfo info, StreamingContext context) : base (info, context) { + protected ThreadInterruptedException(SerializationInfo info, StreamingContext context) : base(info, context) + { } } } diff --git a/src/mscorlib/src/System/Threading/ThreadLocal.cs b/src/mscorlib/src/System/Threading/ThreadLocal.cs index eedf6d0c81..67407e7704 100644 --- a/src/mscorlib/src/System/Threading/ThreadLocal.cs +++ b/src/mscorlib/src/System/Threading/ThreadLocal.cs @@ -36,7 +36,6 @@ namespace System.Threading [DebuggerDisplay("IsValueCreated={IsValueCreated}, Value={ValueForDebugDisplay}, Count={ValuesCountForDebugDisplay}")] public class ThreadLocal<T> : IDisposable { - // a delegate that returns the created value, if null the created value will be default(T) private Func<T> m_valueFactory; @@ -48,10 +47,10 @@ namespace System.Threading // the ThreadLocal<T> instance. // [ThreadStatic] - static LinkedSlotVolatile[] ts_slotArray; + private static LinkedSlotVolatile[] ts_slotArray; [ThreadStatic] - static FinalizationHelper ts_finalizationHelper; + private static FinalizationHelper ts_finalizationHelper; // Slot ID of this ThreadLocal<> instance. We store a bitwise complement of the ID (that is ~ID), which allows us to distinguish // between the case when ID is 0 and an incompletely initialized object, either due to a thread abort in the constructor, or @@ -276,7 +275,7 @@ namespace System.Threading && id < slotArray.Length // Is the table large enough? && (slot = slotArray[id].Value) != null // Has a LinkedSlot object has been allocated for this ID? && m_initialized // Has the instance *still* not been disposed (important for a race condition with Dispose)? - ) + ) { // We verified that the instance has not been disposed *after* we got a reference to the slot. // This guarantees that we have a reference to the right slot. diff --git a/src/mscorlib/src/System/Threading/ThreadPool.cs b/src/mscorlib/src/System/Threading/ThreadPool.cs index ccd528d620..e193967971 100644 --- a/src/mscorlib/src/System/Threading/ThreadPool.cs +++ b/src/mscorlib/src/System/Threading/ThreadPool.cs @@ -33,7 +33,7 @@ namespace System.Threading public static readonly int processorCount = Environment.ProcessorCount; - public static readonly bool tpHosted = ThreadPool.IsThreadPoolHosted(); + public static readonly bool tpHosted = ThreadPool.IsThreadPoolHosted(); public static volatile bool vmTpInitialized; public static bool enableWorkerTracking; @@ -124,7 +124,7 @@ namespace System.Threading private volatile int m_headIndex = START_INDEX; private volatile int m_tailIndex = START_INDEX; - private SpinLock m_foreignLock = new SpinLock(enableThreadOwnerTracking:false); + private SpinLock m_foreignLock = new SpinLock(enableThreadOwnerTracking: false); public void LocalPush(IThreadPoolWorkItem obj) { @@ -158,7 +158,7 @@ namespace System.Threading finally { if (lockTaken) - m_foreignLock.Exit(useMemoryBarrier:true); + m_foreignLock.Exit(useMemoryBarrier: true); } } @@ -200,7 +200,7 @@ namespace System.Threading finally { if (lockTaken) - m_foreignLock.Exit(useMemoryBarrier:false); + m_foreignLock.Exit(useMemoryBarrier: false); } } } @@ -254,7 +254,7 @@ namespace System.Threading finally { if (lockTaken) - m_foreignLock.Exit(useMemoryBarrier:false); + m_foreignLock.Exit(useMemoryBarrier: false); } } } @@ -321,7 +321,7 @@ namespace System.Threading finally { if (lockTaken) - m_foreignLock.Exit(useMemoryBarrier:false); + m_foreignLock.Exit(useMemoryBarrier: false); } } } @@ -366,7 +366,7 @@ namespace System.Threading finally { if (taken) - m_foreignLock.Exit(useMemoryBarrier:false); + m_foreignLock.Exit(useMemoryBarrier: false); } missedSteal = true; @@ -381,10 +381,10 @@ namespace System.Threading internal readonly ConcurrentQueue<IThreadPoolWorkItem> workItems = new ConcurrentQueue<IThreadPoolWorkItem>(); private volatile int numOutstandingThreadRequests = 0; - + public ThreadPoolWorkQueue() { - loggingEnabled = FrameworkEventSource.Log.IsEnabled(EventLevel.Verbose, FrameworkEventSource.Keywords.ThreadPool|FrameworkEventSource.Keywords.ThreadTransfer); + loggingEnabled = FrameworkEventSource.Log.IsEnabled(EventLevel.Verbose, FrameworkEventSource.Keywords.ThreadPool | FrameworkEventSource.Keywords.ThreadTransfer); } public ThreadPoolWorkQueueThreadLocals EnsureCurrentThreadHasQueue() => @@ -401,7 +401,7 @@ namespace System.Threading int count = numOutstandingThreadRequests; while (count < ThreadPoolGlobals.processorCount) { - int prev = Interlocked.CompareExchange(ref numOutstandingThreadRequests, count+1, count); + int prev = Interlocked.CompareExchange(ref numOutstandingThreadRequests, count + 1, count); if (prev == count) { ThreadPool.RequestWorkerThread(); @@ -439,7 +439,7 @@ namespace System.Threading ThreadPoolWorkQueueThreadLocals tl = null; if (!forceGlobal) tl = ThreadPoolWorkQueueThreadLocals.threadLocals; - + if (null != tl) { tl.workStealingQueue.LocalPush(callback); @@ -511,7 +511,7 @@ namespace System.Threading workQueue.MarkThreadRequestSatisfied(); // Has the desire for logging changed since the last time we entered? - workQueue.loggingEnabled = FrameworkEventSource.Log.IsEnabled(EventLevel.Verbose, FrameworkEventSource.Keywords.ThreadPool|FrameworkEventSource.Keywords.ThreadTransfer); + workQueue.loggingEnabled = FrameworkEventSource.Log.IsEnabled(EventLevel.Verbose, FrameworkEventSource.Keywords.ThreadPool | FrameworkEventSource.Keywords.ThreadTransfer); // // Assume that we're going to need another thread if this one returns to the VM. We'll set this to @@ -603,7 +603,7 @@ namespace System.Threading // who waits for the task to complete. // workItem?.MarkAborted(tae); - + // // In this case, the VM is going to request another thread on our behalf. No need to do it twice. // @@ -707,7 +707,7 @@ namespace System.Threading private volatile int m_lock = 0; internal IntPtr GetHandle() => registeredWaitHandle; - + internal void SetHandle(IntPtr handle) { registeredWaitHandle = handle; @@ -731,7 +731,7 @@ namespace System.Threading } internal bool Unregister( - WaitHandle waitObject // object to be notified when all callbacks to delegates have completed + WaitHandle waitObject // object to be notified when all callbacks to delegates have completed ) { bool result = false; @@ -745,7 +745,7 @@ namespace System.Threading // lock(this) cannot be used reliably in Cer since thin lock could be // promoted to syncblock and that is not a guaranteed operation bool bLockTaken = false; - do + do { if (Interlocked.CompareExchange(ref m_lock, 1, 0) == 0) { @@ -841,9 +841,10 @@ namespace System.Threading private static extern bool UnregisterWaitNative(IntPtr handle, SafeHandle waitObject); } - public sealed class RegisteredWaitHandle : MarshalByRefObject { + public sealed class RegisteredWaitHandle : MarshalByRefObject + { private readonly RegisteredWaitHandleSafe internalRegisteredWait; - + internal RegisteredWaitHandle() { internalRegisteredWait = new RegisteredWaitHandleSafe(); @@ -851,23 +852,23 @@ namespace System.Threading internal void SetHandle(IntPtr handle) { - internalRegisteredWait.SetHandle(handle); + internalRegisteredWait.SetHandle(handle); } internal void SetWaitObject(WaitHandle waitObject) { - internalRegisteredWait.SetWaitObject(waitObject); + internalRegisteredWait.SetWaitObject(waitObject); } // This is the only public method on this class public bool Unregister( - WaitHandle waitObject // object to be notified when all callbacks to delegates have completed + WaitHandle waitObject // object to be notified when all callbacks to delegates have completed ) { return internalRegisteredWait.Unregister(waitObject); } } - + public delegate void WaitCallback(Object state); public delegate void WaitOrTimerCallback(Object state, bool timedOut); // signalled or timed out @@ -905,16 +906,16 @@ namespace System.Threading private readonly Object state; #if DEBUG - volatile int executed; + private volatile int executed; ~QueueUserWorkItemCallback() { Debug.Assert( - executed != 0 || Environment.HasShutdownStarted || AppDomain.CurrentDomain.IsFinalizingForUnload(), + executed != 0 || Environment.HasShutdownStarted || AppDomain.CurrentDomain.IsFinalizingForUnload(), "A QueueUserWorkItemCallback was never called!"); } - void MarkExecuted(bool aborted) + private void MarkExecuted(bool aborted) { GC.SuppressFinalize(this); Debug.Assert( @@ -933,7 +934,7 @@ namespace System.Threading void IThreadPoolWorkItem.ExecuteWorkItem() { #if DEBUG - MarkExecuted(aborted:false); + MarkExecuted(aborted: false); #endif // call directly if it is an unsafe call OR EC flow is suppressed if (context == null) @@ -953,7 +954,7 @@ namespace System.Threading #if DEBUG // this workitem didn't execute because we got a ThreadAbortException prior to the call to ExecuteWorkItem. // This counts as being executed for our purposes. - MarkExecuted(aborted:true); + MarkExecuted(aborted: true); #endif } @@ -983,7 +984,7 @@ namespace System.Threading "A QueueUserWorkItemCallbackDefaultContext was never called!"); } - void MarkExecuted(bool aborted) + private void MarkExecuted(bool aborted) { GC.SuppressFinalize(this); Debug.Assert( @@ -1001,7 +1002,7 @@ namespace System.Threading void IThreadPoolWorkItem.ExecuteWorkItem() { #if DEBUG - MarkExecuted(aborted:false); + MarkExecuted(aborted: false); #endif ExecutionContext.Run(ExecutionContext.Default, ccb, this); } @@ -1011,7 +1012,7 @@ namespace System.Threading #if DEBUG // this workitem didn't execute because we got a ThreadAbortException prior to the call to ExecuteWorkItem. // This counts as being executed for our purposes. - MarkExecuted(aborted:true); + MarkExecuted(aborted: true); #endif } @@ -1029,9 +1030,9 @@ namespace System.Threading internal class _ThreadPoolWaitOrTimerCallback { - WaitOrTimerCallback _waitOrTimerCallback; - ExecutionContext _executionContext; - Object _state; + private WaitOrTimerCallback _waitOrTimerCallback; + private ExecutionContext _executionContext; + private Object _state; private static readonly ContextCallback _ccbt = new ContextCallback(WaitOrTimerCallback_Context_t); private static readonly ContextCallback _ccbf = new ContextCallback(WaitOrTimerCallback_Context_f); @@ -1046,23 +1047,23 @@ namespace System.Threading _executionContext = ExecutionContext.Capture(); } } - + private static void WaitOrTimerCallback_Context_t(Object state) => - WaitOrTimerCallback_Context(state, timedOut:true); + WaitOrTimerCallback_Context(state, timedOut: true); private static void WaitOrTimerCallback_Context_f(Object state) => - WaitOrTimerCallback_Context(state, timedOut:false); + WaitOrTimerCallback_Context(state, timedOut: false); private static void WaitOrTimerCallback_Context(Object state, bool timedOut) { _ThreadPoolWaitOrTimerCallback helper = (_ThreadPoolWaitOrTimerCallback)state; helper._waitOrTimerCallback(helper._state, timedOut); } - + // call back helper internal static void PerformWaitOrTimerCallback(Object state, bool timedOut) { - _ThreadPoolWaitOrTimerCallback helper = (_ThreadPoolWaitOrTimerCallback)state; + _ThreadPoolWaitOrTimerCallback helper = (_ThreadPoolWaitOrTimerCallback)state; Debug.Assert(helper != null, "Null state passed to PerformWaitOrTimerCallback!"); // call directly if it is an unsafe call OR EC flow is suppressed if (helper._executionContext == null) @@ -1074,15 +1075,14 @@ namespace System.Threading { ExecutionContext.Run(helper._executionContext, timedOut ? _ccbt : _ccbf, helper); } - } - + } } [CLSCompliant(false)] unsafe public delegate void IOCompletionCallback(uint errorCode, // Error code uint numBytes, // No. of bytes transferred NativeOverlapped* pOVERLAP // ptr to OVERLAP structure - ); + ); public static class ThreadPool { @@ -1114,40 +1114,40 @@ namespace System.Threading [CLSCompliant(false)] [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod public static RegisteredWaitHandle RegisterWaitForSingleObject( // throws RegisterWaitException - WaitHandle waitObject, - WaitOrTimerCallback callBack, - Object state, - uint millisecondsTimeOutInterval, - bool executeOnlyOnce // NOTE: we do not allow other options that allow the callback to be queued as an APC + WaitHandle waitObject, + WaitOrTimerCallback callBack, + Object state, + uint millisecondsTimeOutInterval, + bool executeOnlyOnce // NOTE: we do not allow other options that allow the callback to be queued as an APC ) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - return RegisterWaitForSingleObject(waitObject,callBack,state,millisecondsTimeOutInterval,executeOnlyOnce,ref stackMark,true); + return RegisterWaitForSingleObject(waitObject, callBack, state, millisecondsTimeOutInterval, executeOnlyOnce, ref stackMark, true); } [CLSCompliant(false)] [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject( // throws RegisterWaitException - WaitHandle waitObject, - WaitOrTimerCallback callBack, - Object state, - uint millisecondsTimeOutInterval, - bool executeOnlyOnce // NOTE: we do not allow other options that allow the callback to be queued as an APC + WaitHandle waitObject, + WaitOrTimerCallback callBack, + Object state, + uint millisecondsTimeOutInterval, + bool executeOnlyOnce // NOTE: we do not allow other options that allow the callback to be queued as an APC ) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - return RegisterWaitForSingleObject(waitObject,callBack,state,millisecondsTimeOutInterval,executeOnlyOnce,ref stackMark,false); + return RegisterWaitForSingleObject(waitObject, callBack, state, millisecondsTimeOutInterval, executeOnlyOnce, ref stackMark, false); } private static RegisteredWaitHandle RegisterWaitForSingleObject( // throws RegisterWaitException - WaitHandle waitObject, - WaitOrTimerCallback callBack, - Object state, - uint millisecondsTimeOutInterval, - bool executeOnlyOnce, // NOTE: we do not allow other options that allow the callback to be queued as an APC + WaitHandle waitObject, + WaitOrTimerCallback callBack, + Object state, + uint millisecondsTimeOutInterval, + bool executeOnlyOnce, // NOTE: we do not allow other options that allow the callback to be queued as an APC ref StackCrawlMark stackMark, - bool compressStack + bool compressStack ) { RegisteredWaitHandle registeredWaitHandle = new RegisteredWaitHandle(); @@ -1160,7 +1160,7 @@ namespace System.Threading // this could occur if callback were to fire before SetWaitObject does its addref registeredWaitHandle.SetWaitObject(waitObject); IntPtr nativeRegisteredWaitHandle = RegisterWaitForSingleObjectNative(waitObject, - state, + state, millisecondsTimeOutInterval, executeOnlyOnce, registeredWaitHandle, @@ -1178,102 +1178,102 @@ namespace System.Threading [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod public static RegisteredWaitHandle RegisterWaitForSingleObject( // throws RegisterWaitException - WaitHandle waitObject, - WaitOrTimerCallback callBack, - Object state, - int millisecondsTimeOutInterval, - bool executeOnlyOnce // NOTE: we do not allow other options that allow the callback to be queued as an APC + WaitHandle waitObject, + WaitOrTimerCallback callBack, + Object state, + int millisecondsTimeOutInterval, + bool executeOnlyOnce // NOTE: we do not allow other options that allow the callback to be queued as an APC ) { if (millisecondsTimeOutInterval < -1) throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); Contract.EndContractBlock(); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - return RegisterWaitForSingleObject(waitObject,callBack,state,(UInt32)millisecondsTimeOutInterval,executeOnlyOnce,ref stackMark,true); + return RegisterWaitForSingleObject(waitObject, callBack, state, (UInt32)millisecondsTimeOutInterval, executeOnlyOnce, ref stackMark, true); } [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject( // throws RegisterWaitException - WaitHandle waitObject, - WaitOrTimerCallback callBack, - Object state, - int millisecondsTimeOutInterval, - bool executeOnlyOnce // NOTE: we do not allow other options that allow the callback to be queued as an APC + WaitHandle waitObject, + WaitOrTimerCallback callBack, + Object state, + int millisecondsTimeOutInterval, + bool executeOnlyOnce // NOTE: we do not allow other options that allow the callback to be queued as an APC ) { if (millisecondsTimeOutInterval < -1) throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); Contract.EndContractBlock(); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - return RegisterWaitForSingleObject(waitObject,callBack,state,(UInt32)millisecondsTimeOutInterval,executeOnlyOnce,ref stackMark,false); + return RegisterWaitForSingleObject(waitObject, callBack, state, (UInt32)millisecondsTimeOutInterval, executeOnlyOnce, ref stackMark, false); } [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod public static RegisteredWaitHandle RegisterWaitForSingleObject( // throws RegisterWaitException - WaitHandle waitObject, + WaitHandle waitObject, WaitOrTimerCallback callBack, - Object state, - long millisecondsTimeOutInterval, - bool executeOnlyOnce // NOTE: we do not allow other options that allow the callback to be queued as an APC + Object state, + long millisecondsTimeOutInterval, + bool executeOnlyOnce // NOTE: we do not allow other options that allow the callback to be queued as an APC ) { if (millisecondsTimeOutInterval < -1) throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); Contract.EndContractBlock(); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - return RegisterWaitForSingleObject(waitObject,callBack,state,(UInt32)millisecondsTimeOutInterval,executeOnlyOnce,ref stackMark,true); + return RegisterWaitForSingleObject(waitObject, callBack, state, (UInt32)millisecondsTimeOutInterval, executeOnlyOnce, ref stackMark, true); } [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject( // throws RegisterWaitException - WaitHandle waitObject, + WaitHandle waitObject, WaitOrTimerCallback callBack, - Object state, - long millisecondsTimeOutInterval, - bool executeOnlyOnce // NOTE: we do not allow other options that allow the callback to be queued as an APC + Object state, + long millisecondsTimeOutInterval, + bool executeOnlyOnce // NOTE: we do not allow other options that allow the callback to be queued as an APC ) { if (millisecondsTimeOutInterval < -1) throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); Contract.EndContractBlock(); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - return RegisterWaitForSingleObject(waitObject,callBack,state,(UInt32)millisecondsTimeOutInterval,executeOnlyOnce,ref stackMark,false); + return RegisterWaitForSingleObject(waitObject, callBack, state, (UInt32)millisecondsTimeOutInterval, executeOnlyOnce, ref stackMark, false); } [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod public static RegisteredWaitHandle RegisterWaitForSingleObject( - WaitHandle waitObject, - WaitOrTimerCallback callBack, - Object state, - TimeSpan timeout, - bool executeOnlyOnce + WaitHandle waitObject, + WaitOrTimerCallback callBack, + Object state, + TimeSpan timeout, + bool executeOnlyOnce ) { long tm = (long)timeout.TotalMilliseconds; if (tm < -1) throw new ArgumentOutOfRangeException(nameof(timeout), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); - if (tm > (long) Int32.MaxValue) + if (tm > (long)Int32.MaxValue) throw new ArgumentOutOfRangeException(nameof(timeout), Environment.GetResourceString("ArgumentOutOfRange_LessEqualToIntegerMaxVal")); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - return RegisterWaitForSingleObject(waitObject,callBack,state,(UInt32)tm,executeOnlyOnce,ref stackMark,true); + return RegisterWaitForSingleObject(waitObject, callBack, state, (UInt32)tm, executeOnlyOnce, ref stackMark, true); } [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject( - WaitHandle waitObject, - WaitOrTimerCallback callBack, - Object state, - TimeSpan timeout, - bool executeOnlyOnce + WaitHandle waitObject, + WaitOrTimerCallback callBack, + Object state, + TimeSpan timeout, + bool executeOnlyOnce ) { long tm = (long)timeout.TotalMilliseconds; if (tm < -1) throw new ArgumentOutOfRangeException(nameof(timeout), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); - if (tm > (long) Int32.MaxValue) + if (tm > (long)Int32.MaxValue) throw new ArgumentOutOfRangeException(nameof(timeout), Environment.GetResourceString("ArgumentOutOfRange_LessEqualToIntegerMaxVal")); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - return RegisterWaitForSingleObject(waitObject,callBack,state,(UInt32)tm,executeOnlyOnce,ref stackMark,false); + return RegisterWaitForSingleObject(waitObject, callBack, state, (UInt32)tm, executeOnlyOnce, ref stackMark, false); } public static bool QueueUserWorkItem(WaitCallback callBack) => @@ -1428,7 +1428,7 @@ namespace System.Threading EnsureVMInitializedCore(); // separate out to help with inlining } } - + private static void EnsureVMInitializedCore() { ThreadPool.InitializeVMTp(ref ThreadPoolGlobals.enableWorkerTracking); @@ -1436,7 +1436,7 @@ namespace System.Threading } // Native methods: - + [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern bool SetMinThreadsNative(int workerThreads, int completionPortThreads); @@ -1476,14 +1476,14 @@ namespace System.Threading private static extern void InitializeVMTp(ref bool enableWorkerTracking); [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern IntPtr RegisterWaitForSingleObjectNative( - WaitHandle waitHandle, - Object state, - uint timeOutInterval, - bool executeOnlyOnce, - RegisteredWaitHandle registeredWaitHandle, - ref StackCrawlMark stackMark, - bool compressStack + private static extern IntPtr RegisterWaitForSingleObjectNative( + WaitHandle waitHandle, + Object state, + uint timeOutInterval, + bool executeOnlyOnce, + RegisteredWaitHandle registeredWaitHandle, + ref StackCrawlMark stackMark, + bool compressStack ); @@ -1497,15 +1497,17 @@ namespace System.Threading { if (osHandle == null) throw new ArgumentNullException(nameof(osHandle)); - + bool ret = false; bool mustReleaseSafeHandle = false; RuntimeHelpers.PrepareConstrainedRegions(); - try { + try + { osHandle.DangerousAddRef(ref mustReleaseSafeHandle); ret = BindIOCompletionCallbackNative(osHandle.DangerousGetHandle()); } - finally { + finally + { if (mustReleaseSafeHandle) osHandle.DangerousRelease(); } diff --git a/src/mscorlib/src/System/Threading/ThreadPriority.cs b/src/mscorlib/src/System/Threading/ThreadPriority.cs index 6303c2fd94..64b77ea89d 100644 --- a/src/mscorlib/src/System/Threading/ThreadPriority.cs +++ b/src/mscorlib/src/System/Threading/ThreadPriority.cs @@ -12,12 +12,13 @@ ** =============================================================================*/ -namespace System.Threading { - using System.Threading; +using System.Threading; +namespace System.Threading +{ [Serializable] public enum ThreadPriority - { + { /*========================================================================= ** Constants for thread priorities. =========================================================================*/ @@ -26,6 +27,5 @@ namespace System.Threading { Normal = 2, AboveNormal = 3, Highest = 4 - } } diff --git a/src/mscorlib/src/System/Threading/ThreadStart.cs b/src/mscorlib/src/System/Threading/ThreadStart.cs index e4beddcd75..c065fddbcf 100644 --- a/src/mscorlib/src/System/Threading/ThreadStart.cs +++ b/src/mscorlib/src/System/Threading/ThreadStart.cs @@ -13,9 +13,10 @@ ** =============================================================================*/ -namespace System.Threading { - using System.Threading; +using System.Threading; +namespace System.Threading +{ // Define the delegate // NOTE: If you change the signature here, there is code in COMSynchronization // that invokes this delegate in native. diff --git a/src/mscorlib/src/System/Threading/ThreadStartException.cs b/src/mscorlib/src/System/Threading/ThreadStartException.cs index 33fb460b3d..5b5ee82fc7 100644 --- a/src/mscorlib/src/System/Threading/ThreadStartException.cs +++ b/src/mscorlib/src/System/Threading/ThreadStartException.cs @@ -4,17 +4,17 @@ // -namespace System.Threading -{ - using System; - using System.Runtime.Serialization; - using System.Runtime.InteropServices; +using System; +using System.Runtime.Serialization; +using System.Runtime.InteropServices; +namespace System.Threading +{ [Serializable] - public sealed class ThreadStartException : SystemException + public sealed class ThreadStartException : SystemException { - private ThreadStartException() - : base(Environment.GetResourceString("Arg_ThreadStartException")) + private ThreadStartException() + : base(Environment.GetResourceString("Arg_ThreadStartException")) { SetErrorCode(__HResults.COR_E_THREADSTART); } @@ -26,11 +26,10 @@ namespace System.Threading } //required for serialization - internal ThreadStartException(SerializationInfo info, StreamingContext context) - : base(info, context) + internal ThreadStartException(SerializationInfo info, StreamingContext context) + : base(info, context) { } - } } diff --git a/src/mscorlib/src/System/Threading/ThreadState.cs b/src/mscorlib/src/System/Threading/ThreadState.cs index 2d953f384a..c95772e9a7 100644 --- a/src/mscorlib/src/System/Threading/ThreadState.cs +++ b/src/mscorlib/src/System/Threading/ThreadState.cs @@ -12,12 +12,12 @@ ** =============================================================================*/ -namespace System.Threading { - -[Serializable] -[Flags] +namespace System.Threading +{ + [Serializable] + [Flags] public enum ThreadState - { + { /*========================================================================= ** Constants for thread states. =========================================================================*/ diff --git a/src/mscorlib/src/System/Threading/ThreadStateException.cs b/src/mscorlib/src/System/Threading/ThreadStateException.cs index 97c03ce06c..0df4416a93 100644 --- a/src/mscorlib/src/System/Threading/ThreadStateException.cs +++ b/src/mscorlib/src/System/Threading/ThreadStateException.cs @@ -13,28 +13,34 @@ ** =============================================================================*/ -namespace System.Threading { - using System; - using System.Runtime.Serialization; +using System; +using System.Runtime.Serialization; + +namespace System.Threading +{ [Serializable] - public class ThreadStateException : SystemException { - public ThreadStateException() - : base(Environment.GetResourceString("Arg_ThreadStateException")) { + public class ThreadStateException : SystemException + { + public ThreadStateException() + : base(Environment.GetResourceString("Arg_ThreadStateException")) + { SetErrorCode(__HResults.COR_E_THREADSTATE); } - - public ThreadStateException(String message) - : base(message) { + + public ThreadStateException(String message) + : base(message) + { SetErrorCode(__HResults.COR_E_THREADSTATE); } - - public ThreadStateException(String message, Exception innerException) - : base(message, innerException) { + + public ThreadStateException(String message, Exception innerException) + : base(message, innerException) + { SetErrorCode(__HResults.COR_E_THREADSTATE); } - protected ThreadStateException(SerializationInfo info, StreamingContext context) : base (info, context) { + protected ThreadStateException(SerializationInfo info, StreamingContext context) : base(info, context) + { } } - } diff --git a/src/mscorlib/src/System/Threading/Timeout.cs b/src/mscorlib/src/System/Threading/Timeout.cs index 80bdbccf4e..df1ea5f2bc 100644 --- a/src/mscorlib/src/System/Threading/Timeout.cs +++ b/src/mscorlib/src/System/Threading/Timeout.cs @@ -2,9 +2,11 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Threading { - using System.Threading; - using System; +using System.Threading; +using System; + +namespace System.Threading +{ // A constant used by methods that take a timeout (Object.Wait, Thread.Sleep // etc) to indicate that no timeout should occur. // @@ -15,5 +17,4 @@ namespace System.Threading { public const int Infinite = -1; internal const uint UnsignedInfinite = unchecked((uint)-1); } - } diff --git a/src/mscorlib/src/System/Threading/Timer.cs b/src/mscorlib/src/System/Threading/Timer.cs index 93d2922799..666fe70b32 100644 --- a/src/mscorlib/src/System/Threading/Timer.cs +++ b/src/mscorlib/src/System/Threading/Timer.cs @@ -4,7 +4,7 @@ // -namespace System.Threading +namespace System.Threading { using System; using System.Security; @@ -19,7 +19,7 @@ namespace System.Threading using Microsoft.Win32.SafeHandles; - + public delegate void TimerCallback(Object state); // @@ -43,12 +43,12 @@ namespace System.Threading // // Note that all instance methods of this class require that the caller hold a lock on TimerQueue.Instance. // - class TimerQueue + internal class TimerQueue { #region singleton pattern implementation // The one-and-only TimerQueue for the AppDomain. - static TimerQueue s_queue = new TimerQueue(); + private static TimerQueue s_queue = new TimerQueue(); public static TimerQueue Instance { @@ -100,7 +100,7 @@ namespace System.Threading // // We use a SafeHandle to ensure that the native timer is destroyed when the AppDomain is unloaded. // - class AppDomainTimerSafeHandle : SafeHandleZeroOrMinusOneIsInvalid + private class AppDomainTimerSafeHandle : SafeHandleZeroOrMinusOneIsInvalid { public AppDomainTimerSafeHandle() : base(true) @@ -113,11 +113,11 @@ namespace System.Threading } } - AppDomainTimerSafeHandle m_appDomainTimer; + private AppDomainTimerSafeHandle m_appDomainTimer; - bool m_isAppDomainTimerScheduled; - int m_currentAppDomainTimerStartTicks; - uint m_currentAppDomainTimerDuration; + private bool m_isAppDomainTimerScheduled; + private int m_currentAppDomainTimerStartTicks; + private uint m_currentAppDomainTimerDuration; private bool EnsureAppDomainTimerFiresBy(uint requestedDuration) { @@ -145,13 +145,13 @@ namespace System.Threading // If Pause is underway then do not schedule the timers // A later update during resume will re-schedule - if(m_pauseTicks != 0) + if (m_pauseTicks != 0) { Debug.Assert(!m_isAppDomainTimerScheduled); Debug.Assert(m_appDomainTimer == null); return true; } - + if (m_appDomainTimer == null || m_appDomainTimer.IsInvalid) { Debug.Assert(!m_isAppDomainTimerScheduled); @@ -195,15 +195,15 @@ namespace System.Threading [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] - static extern AppDomainTimerSafeHandle CreateAppDomainTimer(uint dueTime); + private static extern AppDomainTimerSafeHandle CreateAppDomainTimer(uint dueTime); [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] - static extern bool ChangeAppDomainTimer(AppDomainTimerSafeHandle handle, uint dueTime); + private static extern bool ChangeAppDomainTimer(AppDomainTimerSafeHandle handle, uint dueTime); [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] - static extern bool DeleteAppDomainTimer(IntPtr handle); + private static extern bool DeleteAppDomainTimer(IntPtr handle); #endregion @@ -212,10 +212,10 @@ namespace System.Threading // // The list of timers // - TimerQueueTimer m_timers; + private TimerQueueTimer m_timers; - volatile int m_pauseTicks = 0; // Time when Pause was called + private volatile int m_pauseTicks = 0; // Time when Pause was called // @@ -386,7 +386,7 @@ namespace System.Threading // // A timer in our TimerQueue. // - sealed class TimerQueueTimer + internal sealed class TimerQueueTimer { // // All fields of this class are protected by a lock on TimerQueue.Instance. @@ -414,9 +414,9 @@ namespace System.Threading // // Info about the user's callback // - readonly TimerCallback m_timerCallback; - readonly Object m_state; - readonly ExecutionContext m_executionContext; + private readonly TimerCallback m_timerCallback; + private readonly Object m_state; + private readonly ExecutionContext m_executionContext; // @@ -426,9 +426,9 @@ namespace System.Threading // m_callbacksRunning. We set m_notifyWhenNoCallbacksRunning only when m_callbacksRunning // reaches zero. // - int m_callbacksRunning; - volatile bool m_canceled; - volatile WaitHandle m_notifyWhenNoCallbacksRunning; + private int m_callbacksRunning; + private volatile bool m_canceled; + private volatile WaitHandle m_notifyWhenNoCallbacksRunning; internal TimerQueueTimer(TimerCallback timerCallback, object state, uint dueTime, uint period) @@ -612,17 +612,17 @@ namespace System.Threading // change, because any code that happened to be suppressing finalization of Timer objects would now // unwittingly be changing the lifetime of those timers. // - sealed class TimerHolder + internal sealed class TimerHolder { internal TimerQueueTimer m_timer; - - public TimerHolder(TimerQueueTimer timer) - { - m_timer = timer; + + public TimerHolder(TimerQueueTimer timer) + { + m_timer = timer; } - ~TimerHolder() - { + ~TimerHolder() + { // // If shutdown has started, another thread may be suspended while holding the timer lock. // So we can't safely close the timer. @@ -636,7 +636,7 @@ namespace System.Threading if (Environment.HasShutdownStarted || AppDomain.CurrentDomain.IsFinalizingForUnload()) return; - m_timer.Close(); + m_timer.Close(); } public void Close() @@ -651,7 +651,6 @@ namespace System.Threading GC.SuppressFinalize(this); return result; } - } @@ -661,64 +660,64 @@ namespace System.Threading private TimerHolder m_timer; - public Timer(TimerCallback callback, - Object state, - int dueTime, - int period) + public Timer(TimerCallback callback, + Object state, + int dueTime, + int period) { if (dueTime < -1) throw new ArgumentOutOfRangeException(nameof(dueTime), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); - if (period < -1 ) + if (period < -1) throw new ArgumentOutOfRangeException(nameof(period), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); Contract.EndContractBlock(); - TimerSetup(callback,state,(UInt32)dueTime,(UInt32)period); + TimerSetup(callback, state, (UInt32)dueTime, (UInt32)period); } - public Timer(TimerCallback callback, - Object state, - TimeSpan dueTime, - TimeSpan period) - { + public Timer(TimerCallback callback, + Object state, + TimeSpan dueTime, + TimeSpan period) + { long dueTm = (long)dueTime.TotalMilliseconds; if (dueTm < -1) - throw new ArgumentOutOfRangeException(nameof(dueTm),Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); + throw new ArgumentOutOfRangeException(nameof(dueTm), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); if (dueTm > MAX_SUPPORTED_TIMEOUT) - throw new ArgumentOutOfRangeException(nameof(dueTm),Environment.GetResourceString("ArgumentOutOfRange_TimeoutTooLarge")); + throw new ArgumentOutOfRangeException(nameof(dueTm), Environment.GetResourceString("ArgumentOutOfRange_TimeoutTooLarge")); long periodTm = (long)period.TotalMilliseconds; if (periodTm < -1) - throw new ArgumentOutOfRangeException(nameof(periodTm),Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); + throw new ArgumentOutOfRangeException(nameof(periodTm), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); if (periodTm > MAX_SUPPORTED_TIMEOUT) - throw new ArgumentOutOfRangeException(nameof(periodTm),Environment.GetResourceString("ArgumentOutOfRange_PeriodTooLarge")); + throw new ArgumentOutOfRangeException(nameof(periodTm), Environment.GetResourceString("ArgumentOutOfRange_PeriodTooLarge")); - TimerSetup(callback,state,(UInt32)dueTm,(UInt32)periodTm); + TimerSetup(callback, state, (UInt32)dueTm, (UInt32)periodTm); } [CLSCompliant(false)] - public Timer(TimerCallback callback, - Object state, - UInt32 dueTime, - UInt32 period) + public Timer(TimerCallback callback, + Object state, + UInt32 dueTime, + UInt32 period) { - TimerSetup(callback,state,dueTime,period); + TimerSetup(callback, state, dueTime, period); } - public Timer(TimerCallback callback, - Object state, - long dueTime, - long period) + public Timer(TimerCallback callback, + Object state, + long dueTime, + long period) { if (dueTime < -1) - throw new ArgumentOutOfRangeException(nameof(dueTime),Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); + throw new ArgumentOutOfRangeException(nameof(dueTime), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); if (period < -1) - throw new ArgumentOutOfRangeException(nameof(period),Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); + throw new ArgumentOutOfRangeException(nameof(period), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); if (dueTime > MAX_SUPPORTED_TIMEOUT) - throw new ArgumentOutOfRangeException(nameof(dueTime),Environment.GetResourceString("ArgumentOutOfRange_TimeoutTooLarge")); + throw new ArgumentOutOfRangeException(nameof(dueTime), Environment.GetResourceString("ArgumentOutOfRange_TimeoutTooLarge")); if (period > MAX_SUPPORTED_TIMEOUT) - throw new ArgumentOutOfRangeException(nameof(period),Environment.GetResourceString("ArgumentOutOfRange_PeriodTooLarge")); + throw new ArgumentOutOfRangeException(nameof(period), Environment.GetResourceString("ArgumentOutOfRange_PeriodTooLarge")); Contract.EndContractBlock(); - TimerSetup(callback,state,(UInt32) dueTime, (UInt32) period); + TimerSetup(callback, state, (UInt32)dueTime, (UInt32)period); } public Timer(TimerCallback callback) @@ -727,12 +726,12 @@ namespace System.Threading int period = -1; // Change after a timer instance is created. This is to avoid the potential // for a timer to be fired before the returned value is assigned to the variable, // potentially causing the callback to reference a bogus value (if passing the timer to the callback). - + TimerSetup(callback, this, (UInt32)dueTime, (UInt32)period); } private void TimerSetup(TimerCallback callback, - Object state, + Object state, UInt32 dueTime, UInt32 period) { @@ -742,13 +741,13 @@ namespace System.Threading m_timer = new TimerHolder(new TimerQueueTimer(callback, state, dueTime, period)); } - + public bool Change(int dueTime, int period) { - if (dueTime < -1 ) - throw new ArgumentOutOfRangeException(nameof(dueTime),Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); + if (dueTime < -1) + throw new ArgumentOutOfRangeException(nameof(dueTime), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); if (period < -1) - throw new ArgumentOutOfRangeException(nameof(period),Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); + throw new ArgumentOutOfRangeException(nameof(period), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); Contract.EndContractBlock(); return m_timer.m_timer.Change((UInt32)dueTime, (UInt32)period); @@ -756,7 +755,7 @@ namespace System.Threading public bool Change(TimeSpan dueTime, TimeSpan period) { - return Change((long) dueTime.TotalMilliseconds, (long) period.TotalMilliseconds); + return Change((long)dueTime.TotalMilliseconds, (long)period.TotalMilliseconds); } [CLSCompliant(false)] @@ -767,7 +766,7 @@ namespace System.Threading public bool Change(long dueTime, long period) { - if (dueTime < -1 ) + if (dueTime < -1) throw new ArgumentOutOfRangeException(nameof(dueTime), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); if (period < -1) throw new ArgumentOutOfRangeException(nameof(period), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); @@ -779,16 +778,16 @@ namespace System.Threading return m_timer.m_timer.Change((UInt32)dueTime, (UInt32)period); } - + public bool Dispose(WaitHandle notifyObject) { - if (notifyObject==null) + if (notifyObject == null) throw new ArgumentNullException(nameof(notifyObject)); Contract.EndContractBlock(); return m_timer.Close(notifyObject); } - + public void Dispose() { m_timer.Close(); diff --git a/src/mscorlib/src/System/Threading/Volatile.cs b/src/mscorlib/src/System/Threading/Volatile.cs index c94a69ab7b..620aa5ee47 100644 --- a/src/mscorlib/src/System/Threading/Volatile.cs +++ b/src/mscorlib/src/System/Threading/Volatile.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. // + using System; using System.Runtime.InteropServices; using System.Runtime.Versioning; diff --git a/src/mscorlib/src/System/Threading/WaitHandle.cs b/src/mscorlib/src/System/Threading/WaitHandle.cs index d4dcd710be..7ffd4b8d5a 100644 --- a/src/mscorlib/src/System/Threading/WaitHandle.cs +++ b/src/mscorlib/src/System/Threading/WaitHandle.cs @@ -26,8 +26,9 @@ namespace System.Threading using System.Diagnostics.CodeAnalysis; using Win32Native = Microsoft.Win32.Win32Native; - public abstract class WaitHandle : MarshalByRefObject, IDisposable { - public const int WaitTimeout = 0x102; + public abstract class WaitHandle : MarshalByRefObject, IDisposable + { + public const int WaitTimeout = 0x102; private const int MAX_WAITHANDLES = 64; @@ -57,7 +58,7 @@ namespace System.Threading NameInvalid } - protected WaitHandle() + protected WaitHandle() { Init(); } @@ -68,12 +69,12 @@ namespace System.Threading waitHandle = InvalidHandle; hasThreadAffinity = false; } - - + + [Obsolete("Use the SafeWaitHandle property instead.")] - public virtual IntPtr Handle + public virtual IntPtr Handle { - get { return safeWaitHandle == null ? InvalidHandle : safeWaitHandle.DangerousGetHandle();} + get { return safeWaitHandle == null ? InvalidHandle : safeWaitHandle.DangerousGetHandle(); } set { if (value == InvalidHandle) @@ -92,13 +93,13 @@ namespace System.Threading } else { - safeWaitHandle = new SafeWaitHandle(value, true); + safeWaitHandle = new SafeWaitHandle(value, true); } waitHandle = value; } } - public SafeWaitHandle SafeWaitHandle + public SafeWaitHandle SafeWaitHandle { get { @@ -111,23 +112,23 @@ namespace System.Threading set { - // Set safeWaitHandle and waitHandle in a CER so we won't take - // a thread abort between the statements and leave the wait - // handle in an invalid state. Note this routine is not thread - // safe however. - RuntimeHelpers.PrepareConstrainedRegions(); + // Set safeWaitHandle and waitHandle in a CER so we won't take + // a thread abort between the statements and leave the wait + // handle in an invalid state. Note this routine is not thread + // safe however. + RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { if (value == null) { - safeWaitHandle = null; - waitHandle = InvalidHandle; + safeWaitHandle = null; + waitHandle = InvalidHandle; } else { - safeWaitHandle = value; - waitHandle = safeWaitHandle.DangerousGetHandle(); + safeWaitHandle = value; + waitHandle = safeWaitHandle.DangerousGetHandle(); } } } @@ -147,41 +148,41 @@ namespace System.Threading safeWaitHandle = handle; waitHandle = handle.DangerousGetHandle(); } - - public virtual bool WaitOne (int millisecondsTimeout, bool exitContext) + + public virtual bool WaitOne(int millisecondsTimeout, bool exitContext) { if (millisecondsTimeout < -1) { throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); } Contract.EndContractBlock(); - return WaitOne((long)millisecondsTimeout,exitContext); + return WaitOne((long)millisecondsTimeout, exitContext); } - public virtual bool WaitOne (TimeSpan timeout, bool exitContext) + public virtual bool WaitOne(TimeSpan timeout, bool exitContext) { long tm = (long)timeout.TotalMilliseconds; - if (-1 > tm || (long) Int32.MaxValue < tm) + if (-1 > tm || (long)Int32.MaxValue < tm) { throw new ArgumentOutOfRangeException(nameof(timeout), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); } - return WaitOne(tm,exitContext); + return WaitOne(tm, exitContext); } - public virtual bool WaitOne () + public virtual bool WaitOne() { //Infinite Timeout - return WaitOne(-1,false); + return WaitOne(-1, false); } public virtual bool WaitOne(int millisecondsTimeout) { - return WaitOne(millisecondsTimeout, false); + return WaitOne(millisecondsTimeout, false); } public virtual bool WaitOne(TimeSpan timeout) { - return WaitOne(timeout, false); + return WaitOne(timeout, false); } [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread-safety.")] @@ -199,16 +200,16 @@ namespace System.Threading Contract.EndContractBlock(); int ret = WaitOneNative(waitableSafeHandle, (uint)millisecondsTimeout, hasThreadAffinity, exitContext); - if(AppDomainPauseManager.IsPaused) + if (AppDomainPauseManager.IsPaused) AppDomainPauseManager.ResumeEvent.WaitOneWithoutFAS(); - + if (ret == WAIT_ABANDONED) { ThrowAbandonedMutexException(); } return (ret != WaitTimeout); } - + internal bool WaitOneWithoutFAS() { // version of waitone without fast application switch (FAS) support @@ -226,11 +227,11 @@ namespace System.Threading ThrowAbandonedMutexException(); } return (ret != WaitTimeout); - } + } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern int WaitOneNative(SafeHandle waitableSafeHandle, uint millisecondsTimeout, bool hasThreadAffinity, bool exitContext); - + /*======================================================================== ** Waits for signal from all the objects. ** timeout indicates how long to wait before the method returns. @@ -239,8 +240,8 @@ namespace System.Threading ** If exitContext is true then the synchronization domain for the context ** (if in a synchronized context) is exited before the wait and reacquired ========================================================================*/ - - [MethodImplAttribute(MethodImplOptions.InternalCall)] + + [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern int WaitMultiple(WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext, bool WaitAll); public static bool WaitAll(WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext) @@ -249,7 +250,7 @@ namespace System.Threading { throw new ArgumentNullException(nameof(waitHandles), Environment.GetResourceString("ArgumentNull_Waithandles")); } - if(waitHandles.Length == 0) + if (waitHandles.Length == 0) { // // Some history: in CLR 1.0 and 1.1, we threw ArgumentException in this case, which was correct. @@ -272,7 +273,7 @@ namespace System.Threading } Contract.EndContractBlock(); WaitHandle[] internalWaitHandles = new WaitHandle[waitHandles.Length]; - for (int i = 0; i < waitHandles.Length; i ++) + for (int i = 0; i < waitHandles.Length; i++) { WaitHandle waitHandle = waitHandles[i]; @@ -288,51 +289,51 @@ namespace System.Threading int ret = WaitMultiple(internalWaitHandles, millisecondsTimeout, exitContext, true /* waitall*/ ); - if(AppDomainPauseManager.IsPaused) + if (AppDomainPauseManager.IsPaused) AppDomainPauseManager.ResumeEvent.WaitOneWithoutFAS(); - if ((WAIT_ABANDONED <= ret) && (WAIT_ABANDONED+internalWaitHandles.Length > ret)) + if ((WAIT_ABANDONED <= ret) && (WAIT_ABANDONED + internalWaitHandles.Length > ret)) { //In the case of WaitAll the OS will only provide the // information that mutex was abandoned. // It won't tell us which one. So we can't set the Index or provide access to the Mutex ThrowAbandonedMutexException(); - } + } GC.KeepAlive(internalWaitHandles); return (ret != WaitTimeout); } public static bool WaitAll( - WaitHandle[] waitHandles, + WaitHandle[] waitHandles, TimeSpan timeout, bool exitContext) { long tm = (long)timeout.TotalMilliseconds; - if (-1 > tm || (long) Int32.MaxValue < tm) + if (-1 > tm || (long)Int32.MaxValue < tm) { throw new ArgumentOutOfRangeException(nameof(timeout), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); } - return WaitAll(waitHandles,(int)tm, exitContext); + return WaitAll(waitHandles, (int)tm, exitContext); } - + /*======================================================================== ** Shorthand for WaitAll with timeout = Timeout.Infinite and exitContext = true ========================================================================*/ public static bool WaitAll(WaitHandle[] waitHandles) { - return WaitAll(waitHandles, Timeout.Infinite, true); + return WaitAll(waitHandles, Timeout.Infinite, true); } public static bool WaitAll(WaitHandle[] waitHandles, int millisecondsTimeout) { - return WaitAll(waitHandles, millisecondsTimeout, true); + return WaitAll(waitHandles, millisecondsTimeout, true); } public static bool WaitAll(WaitHandle[] waitHandles, TimeSpan timeout) { - return WaitAll(waitHandles, timeout, true); + return WaitAll(waitHandles, timeout, true); } @@ -344,14 +345,14 @@ namespace System.Threading ** If exitContext is true then the synchronization domain for the context ** (if in a synchronized context) is exited before the wait and reacquired ========================================================================*/ - + public static int WaitAny(WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext) { - if (waitHandles==null) + if (waitHandles == null) { throw new ArgumentNullException(nameof(waitHandles), Environment.GetResourceString("ArgumentNull_Waithandles")); } - if(waitHandles.Length == 0) + if (waitHandles.Length == 0) { throw new ArgumentException(Environment.GetResourceString("Argument_EmptyWaithandleArray")); } @@ -365,7 +366,7 @@ namespace System.Threading } Contract.EndContractBlock(); WaitHandle[] internalWaitHandles = new WaitHandle[waitHandles.Length]; - for (int i = 0; i < waitHandles.Length; i ++) + for (int i = 0; i < waitHandles.Length; i++) { WaitHandle waitHandle = waitHandles[i]; @@ -380,41 +381,41 @@ namespace System.Threading #endif int ret = WaitMultiple(internalWaitHandles, millisecondsTimeout, exitContext, false /* waitany*/ ); - if(AppDomainPauseManager.IsPaused) + if (AppDomainPauseManager.IsPaused) AppDomainPauseManager.ResumeEvent.WaitOneWithoutFAS(); - if ((WAIT_ABANDONED <= ret) && (WAIT_ABANDONED+internalWaitHandles.Length > ret)) + if ((WAIT_ABANDONED <= ret) && (WAIT_ABANDONED + internalWaitHandles.Length > ret)) { - int mutexIndex = ret -WAIT_ABANDONED; - if(0 <= mutexIndex && mutexIndex < internalWaitHandles.Length) + int mutexIndex = ret - WAIT_ABANDONED; + if (0 <= mutexIndex && mutexIndex < internalWaitHandles.Length) { - ThrowAbandonedMutexException(mutexIndex,internalWaitHandles[mutexIndex]); + ThrowAbandonedMutexException(mutexIndex, internalWaitHandles[mutexIndex]); } else { ThrowAbandonedMutexException(); } } - + GC.KeepAlive(internalWaitHandles); - return ret; + return ret; } public static int WaitAny( - WaitHandle[] waitHandles, + WaitHandle[] waitHandles, TimeSpan timeout, bool exitContext) { long tm = (long)timeout.TotalMilliseconds; - if (-1 > tm || (long) Int32.MaxValue < tm) + if (-1 > tm || (long)Int32.MaxValue < tm) { throw new ArgumentOutOfRangeException(nameof(timeout), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); } - return WaitAny(waitHandles,(int)tm, exitContext); + return WaitAny(waitHandles, (int)tm, exitContext); } public static int WaitAny(WaitHandle[] waitHandles, TimeSpan timeout) { - return WaitAny(waitHandles, timeout, true); + return WaitAny(waitHandles, timeout, true); } @@ -428,7 +429,7 @@ namespace System.Threading public static int WaitAny(WaitHandle[] waitHandles, int millisecondsTimeout) { - return WaitAny(waitHandles, millisecondsTimeout, true); + return WaitAny(waitHandles, millisecondsTimeout, true); } /*================================================= @@ -437,9 +438,9 @@ namespace System.Threading == ==================================================*/ #if !PLATFORM_UNIX - [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern int SignalAndWaitOne(SafeWaitHandle waitHandleToSignal,SafeWaitHandle waitHandleToWaitOn, int millisecondsTimeout, - bool hasThreadAffinity, bool exitContext); + [MethodImplAttribute(MethodImplOptions.InternalCall)] + private static extern int SignalAndWaitOne(SafeWaitHandle waitHandleToSignal, SafeWaitHandle waitHandleToWaitOn, int millisecondsTimeout, + bool hasThreadAffinity, bool exitContext); #endif // !PLATFORM_UNIX public static bool SignalAndWait( @@ -449,7 +450,7 @@ namespace System.Threading #if PLATFORM_UNIX throw new PlatformNotSupportedException(); #else - return SignalAndWait(toSignal,toWaitOn,-1,false); + return SignalAndWait(toSignal, toWaitOn, -1, false); #endif } @@ -463,11 +464,11 @@ namespace System.Threading throw new PlatformNotSupportedException(); #else long tm = (long)timeout.TotalMilliseconds; - if (-1 > tm || (long) Int32.MaxValue < tm) + if (-1 > tm || (long)Int32.MaxValue < tm) { throw new ArgumentOutOfRangeException(nameof(timeout), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); } - return SignalAndWait(toSignal,toWaitOn,(int)tm,exitContext); + return SignalAndWait(toSignal, toWaitOn, (int)tm, exitContext); #endif } @@ -481,11 +482,11 @@ namespace System.Threading #if PLATFORM_UNIX throw new PlatformNotSupportedException(); #else - if(null == toSignal) + if (null == toSignal) { throw new ArgumentNullException(nameof(toSignal)); } - if(null == toWaitOn) + if (null == toWaitOn) { throw new ArgumentNullException(nameof(toWaitOn)); } @@ -496,21 +497,21 @@ namespace System.Threading Contract.EndContractBlock(); //NOTE: This API is not supporting Pause/Resume as it's not exposed in CoreCLR (not in WP or SL) - int ret = SignalAndWaitOne(toSignal.safeWaitHandle,toWaitOn.safeWaitHandle,millisecondsTimeout, - toWaitOn.hasThreadAffinity,exitContext); + int ret = SignalAndWaitOne(toSignal.safeWaitHandle, toWaitOn.safeWaitHandle, millisecondsTimeout, + toWaitOn.hasThreadAffinity, exitContext); - if(WAIT_ABANDONED == ret) + if (WAIT_ABANDONED == ret) { ThrowAbandonedMutexException(); } - if(ERROR_TOO_MANY_POSTS == ret) + if (ERROR_TOO_MANY_POSTS == ret) { throw new InvalidOperationException(Environment.GetResourceString("Threading.WaitHandleTooManyPosts")); } //Object was signaled - if(WAIT_OBJECT_0 == ret) + if (WAIT_OBJECT_0 == ret) { return true; } @@ -535,7 +536,7 @@ namespace System.Threading Dispose(true); GC.SuppressFinalize(this); } - + protected virtual void Dispose(bool explicitDisposing) { if (safeWaitHandle != null) diff --git a/src/mscorlib/src/System/Threading/WaitHandleCannotBeOpenedException.cs b/src/mscorlib/src/System/Threading/WaitHandleCannotBeOpenedException.cs index 68445a78d9..acdb19cfac 100644 --- a/src/mscorlib/src/System/Threading/WaitHandleCannotBeOpenedException.cs +++ b/src/mscorlib/src/System/Threading/WaitHandleCannotBeOpenedException.cs @@ -3,21 +3,23 @@ // See the LICENSE file in the project root for more information. // -namespace System.Threading -{ - using System; - using System.Runtime.Serialization; - using System.Runtime.InteropServices; +using System; +using System.Runtime.Serialization; +using System.Runtime.InteropServices; + +namespace System.Threading +{ [Serializable] [ComVisibleAttribute(false)] - public class WaitHandleCannotBeOpenedException : ApplicationException { - public WaitHandleCannotBeOpenedException() : base(Environment.GetResourceString("Threading.WaitHandleCannotBeOpenedException")) + public class WaitHandleCannotBeOpenedException : ApplicationException + { + public WaitHandleCannotBeOpenedException() : base(Environment.GetResourceString("Threading.WaitHandleCannotBeOpenedException")) { SetErrorCode(__HResults.COR_E_WAITHANDLECANNOTBEOPENED); } - + public WaitHandleCannotBeOpenedException(String message) : base(message) { SetErrorCode(__HResults.COR_E_WAITHANDLECANNOTBEOPENED); @@ -28,7 +30,7 @@ namespace System.Threading SetErrorCode(__HResults.COR_E_WAITHANDLECANNOTBEOPENED); } - protected WaitHandleCannotBeOpenedException(SerializationInfo info, StreamingContext context) : base (info, context) + protected WaitHandleCannotBeOpenedException(SerializationInfo info, StreamingContext context) : base(info, context) { } } |