bool isValid = (bool)_validateTypeAndReturnDetails.Invoke(null, BindingFlags.DoNotWrapExceptions, binder: null, parameters: parameters, culture: null)!;
if (!isValid)
{
- throw new COMException(); //E_FAIL
+ throw new COMException(); // E_FAIL
}
var license = (IDisposable?)parameters[2];
var licenseKey = (string?)parameters[3];
if (licenseKey == null)
{
- throw new COMException(); //E_FAIL
+ throw new COMException(); // E_FAIL
}
return licenseKey;
internal IEnumerator<T> GetEnumerator<T>()
{
- //! Warning: "this" is an array, not an SZArrayHelper. See comments above
- //! or you may introduce a security hole!
+ // ! Warning: "this" is an array, not an SZArrayHelper. See comments above
+ // ! or you may introduce a security hole!
T[] _this = Unsafe.As<T[]>(this);
return _this.Length == 0 ? SZGenericArrayEnumerator<T>.Empty : new SZGenericArrayEnumerator<T>(_this);
}
private void CopyTo<T>(T[] array, int index)
{
- //! Warning: "this" is an array, not an SZArrayHelper. See comments above
- //! or you may introduce a security hole!
+ // ! Warning: "this" is an array, not an SZArrayHelper. See comments above
+ // ! or you may introduce a security hole!
T[] _this = Unsafe.As<T[]>(this);
Array.Copy(_this, 0, array, index, _this.Length);
internal int get_Count<T>()
{
- //! Warning: "this" is an array, not an SZArrayHelper. See comments above
- //! or you may introduce a security hole!
+ // ! Warning: "this" is an array, not an SZArrayHelper. See comments above
+ // ! or you may introduce a security hole!
T[] _this = Unsafe.As<T[]>(this);
return _this.Length;
}
internal T get_Item<T>(int index)
{
- //! Warning: "this" is an array, not an SZArrayHelper. See comments above
- //! or you may introduce a security hole!
+ // ! Warning: "this" is an array, not an SZArrayHelper. See comments above
+ // ! or you may introduce a security hole!
T[] _this = Unsafe.As<T[]>(this);
if ((uint)index >= (uint)_this.Length)
{
internal void set_Item<T>(int index, T value)
{
- //! Warning: "this" is an array, not an SZArrayHelper. See comments above
- //! or you may introduce a security hole!
+ // ! Warning: "this" is an array, not an SZArrayHelper. See comments above
+ // ! or you may introduce a security hole!
T[] _this = Unsafe.As<T[]>(this);
if ((uint)index >= (uint)_this.Length)
{
private bool Contains<T>(T value)
{
- //! Warning: "this" is an array, not an SZArrayHelper. See comments above
- //! or you may introduce a security hole!
+ // ! Warning: "this" is an array, not an SZArrayHelper. See comments above
+ // ! or you may introduce a security hole!
T[] _this = Unsafe.As<T[]>(this);
return Array.IndexOf(_this, value, 0, _this.Length) >= 0;
}
private void Clear<T>()
{
- //! Warning: "this" is an array, not an SZArrayHelper. See comments above
- //! or you may introduce a security hole!
+ // ! Warning: "this" is an array, not an SZArrayHelper. See comments above
+ // ! or you may introduce a security hole!
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
private int IndexOf<T>(T value)
{
- //! Warning: "this" is an array, not an SZArrayHelper. See comments above
- //! or you may introduce a security hole!
+ // ! Warning: "this" is an array, not an SZArrayHelper. See comments above
+ // ! or you may introduce a security hole!
T[] _this = Unsafe.As<T[]>(this);
return Array.IndexOf(_this, value, 0, _this.Length);
}
List<Attribute> attributeList = new List<Attribute>();
CopyToArrayList(attributeList, attributes, types);
- //if this is an index we need to get the parameter types to help disambiguate
+ // if this is an index we need to get the parameter types to help disambiguate
Type[] indexParamTypes = GetIndexParameterTypes(element);
if (!usage.Inherited)
return false;
- //if this is an index we need to get the parameter types to help disambiguate
+ // if this is an index we need to get the parameter types to help disambiguate
Type[] indexParamTypes = GetIndexParameterTypes(element);
PropertyInfo? baseProp = GetParentDefinition(element, indexParamTypes);
return rtPropAccessor.DeclaringType!.GetProperty(
property.Name,
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly,
- null, //will use default binder
+ null, // will use default binder
property.PropertyType,
- propertyParameters, //used for index properties
+ propertyParameters, // used for index properties
null);
}
}
}
}
- private MethodBase? _exceptionMethod; //Needed for serialization.
+ private MethodBase? _exceptionMethod; // Needed for serialization.
internal string? _message;
private IDictionary? _data;
private readonly Exception? _innerException;
private string? _helpURL;
private object? _stackTrace;
private object? _watsonBuckets;
- private string? _stackTraceString; //Needed for serialization.
+ private string? _stackTraceString; // Needed for serialization.
private string? _remoteStackTraceString;
#pragma warning disable 414 // Fields are not used from managed.
#pragma warning disable CA1823
//
public static void Collect()
{
- //-1 says to GC all generations.
+ // -1 says to GC all generations.
_Collect(-1, (int)InternalGCCollectionMode.Blocking);
}
**
===========================================================*/
-//This class contains only static members and doesn't require serialization.
-
using System.Runtime.CompilerServices;
namespace System
**
===========================================================*/
-//This class contains only static members and doesn't require serialization.
-
using System.Runtime.CompilerServices;
namespace System
MethodAttributes methAttr = RuntimeMethodHandle.GetAttributes(associateMethodHandle);
// ECMA MethodSemantics: "All methods for a given Property or Event shall have the same accessibility
- //(ie the MemberAccessMask subfield of their Flags row) and cannot be CompilerControlled [CLS]"
+ // (ie the MemberAccessMask subfield of their Flags row) and cannot be CompilerControlled [CLS]"
// Consequently, a property may be composed of public and private methods. If the declared type !=
// the reflected type, the private methods should not be exposed. Note that this implies that the
// identity of a property includes it's reflected type.
Debug.Assert(pca.BaseType == typeof(Attribute), "Pseudo CA Error");
AttributeUsageAttribute usage = CustomAttribute.GetAttributeUsage(pca);
Debug.Assert(usage.Inherited == false, "Pseudo CA Error");
- //AllowMultiple is true for TypeForwardedToAttribute
- //Debug.Assert(usage.AllowMultiple == false, "Pseudo CA Error");
+ // AllowMultiple is true for TypeForwardedToAttribute
+ // Debug.Assert(usage.AllowMultiple == false, "Pseudo CA Error");
}
#endregion
m_code = dynamicILInfo.Code;
m_localSignature = dynamicILInfo.LocalSignature;
m_exceptionHeader = dynamicILInfo.Exceptions;
- //m_exceptions = dynamicILInfo.Exceptions;
+ // m_exceptions = dynamicILInfo.Exceptions;
m_scope = dynamicILInfo.DynamicScope;
m_method = dynamicILInfo.DynamicMethod;
public override Type UnderlyingSystemType => GetEnumUnderlyingType();
- //ICustomAttributeProvider
+ // ICustomAttributeProvider
public override object[] GetCustomAttributes(bool inherit)
{
return m_typeBuilder.GetCustomAttributes(inherit);
ModuleBuilder mod, // the module containing this EventBuilder
string name, // Event name
EventAttributes attr, // event attribute such as Public, Private, and Protected defined above
- //int eventType, // event type
+ // int eventType, // event type
TypeBuilder type, // containing type
EventToken evToken)
{
private int m_exceptionCount;
private int m_currExcStackCount;
- private __ExceptionInfo[] m_exceptions; //This is the list of all of the exceptions in this ILStream.
- private __ExceptionInfo[] m_currExcStack; //This is the stack of exceptions which we're currently in.
+ private __ExceptionInfo[] m_exceptions; // This is the list of all of the exceptions in this ILStream.
+ private __ExceptionInfo[] m_currExcStack; // This is the stack of exceptions which we're currently in.
internal ScopeTree m_ScopeTree; // this variable tracks all debugging scope information
internal LineNumberInfo m_LineNumberInfo; // this variable tracks all line number information
if (m_length == 0)
return null;
- //Allocate space for the new array.
+ // Allocate space for the new array.
byte[] newBytes = new byte[m_length];
- //Copy the data from the old array
+ // Copy the data from the old array
Array.Copy(m_ILStream, 0, newBytes, 0, m_length);
- //Do the fixups.
- //This involves iterating over all of the labels and
- //replacing them with their proper values.
+ // Do the fixups.
+ // This involves iterating over all of the labels and
+ // replacing them with their proper values.
for (int i = 0; i < m_fixupCount; i++)
{
__FixupData fixupData = m_fixupData[i];
int updateAddr = GetLabelPos(fixupData.m_fixupLabel) - (fixupData.m_fixupPos + fixupData.m_fixupInstSize);
- //Handle single byte instructions
- //Throw an exception if they're trying to store a jump in a single byte instruction that doesn't fit.
+ // Handle single byte instructions
+ // Throw an exception if they're trying to store a jump in a single byte instruction that doesn't fit.
if (fixupData.m_fixupInstSize == 1)
{
- //Verify that our one-byte arg will fit into a Signed Byte.
+ // Verify that our one-byte arg will fit into a Signed Byte.
if (updateAddr < sbyte.MinValue || updateAddr > sbyte.MaxValue)
{
throw new NotSupportedException(SR.Format(SR.NotSupported_IllegalOneByteBranch, fixupData.m_fixupPos, updateAddr));
}
- //Place the one-byte arg
+ // Place the one-byte arg
newBytes[fixupData.m_fixupPos] = (byte)updateAddr;
}
else
{
- //Place the four-byte arg
+ // Place the four-byte arg
BinaryPrimitives.WriteInt32LittleEndian(newBytes.AsSpan(fixupData.m_fixupPos), updateAddr);
}
}
}
else
{
- //Handle stloc_1, ldloc_1
+ // Handle stloc_1, ldloc_1
if (tempVal > byte.MaxValue)
{
throw new InvalidOperationException(SR.InvalidOperation_BadInstructionOrIndexOutOfBound);
Emit(OpCodes.Endfinally);
}
- //Check if we've already set this label.
- //The only reason why we might have set this is if we have a finally block.
+ // Check if we've already set this label.
+ // The only reason why we might have set this is if we have a finally block.
Label label = m_labelList[endLabel.GetLabelValue()] != -1
? current.m_finallyEndLabel
int labelIndex = loc.GetLabelValue();
- //This should never happen.
+ // This should never happen.
if (labelIndex < 0 || labelIndex >= m_labelList.Length)
{
throw new ArgumentException(SR.Argument_InvalidLabel);
}
else
{
- Emit(OpCodes.Ldarg, (short)0); //Load the this ref.
+ Emit(OpCodes.Ldarg, (short)0); // Load the this ref.
Emit(OpCodes.Ldfld, fld);
}
Type[] parameterTypes = new Type[1];
internal sealed class __ExceptionInfo
{
- internal const int None = 0x0000; //COR_ILEXCEPTION_CLAUSE_NONE
- internal const int Filter = 0x0001; //COR_ILEXCEPTION_CLAUSE_FILTER
- internal const int Finally = 0x0002; //COR_ILEXCEPTION_CLAUSE_FINALLY
- internal const int Fault = 0x0004; //COR_ILEXCEPTION_CLAUSE_FAULT
- internal const int PreserveStack = 0x0004; //COR_ILEXCEPTION_CLAUSE_PRESERVESTACK
+ internal const int None = 0x0000; // COR_ILEXCEPTION_CLAUSE_NONE
+ internal const int Filter = 0x0001; // COR_ILEXCEPTION_CLAUSE_FILTER
+ internal const int Finally = 0x0002; // COR_ILEXCEPTION_CLAUSE_FINALLY
+ internal const int Fault = 0x0004; // COR_ILEXCEPTION_CLAUSE_FAULT
+ internal const int PreserveStack = 0x0004; // COR_ILEXCEPTION_CLAUSE_PRESERVESTACK
internal const int State_Try = 0;
internal const int State_Filter = 1;
}
- //=========================================================================================
+ // =========================================================================================
// Public interface methods start here. (Well actually, they're all NotSupported
// stubs since that's what they are on the real ISymWrapper.dll.)
- //=========================================================================================
+ // =========================================================================================
//------------------------------------------------------------------------------
// SetSource() wrapper
// Define delegates for the unmanaged COM methods we invoke.
//------------------------------------------------------------------------------
private delegate int DInitialize(ISymUnmanagedWriter* pthis,
- IntPtr emitter, //IUnknown*
- [MarshalAs(UnmanagedType.LPWStr)] string filename, //WCHAR*
- IntPtr pIStream, //IStream*
+ IntPtr emitter, // IUnknown*
+ [MarshalAs(UnmanagedType.LPWStr)] string filename, // WCHAR*
+ IntPtr pIStream, // IStream*
[MarshalAs(UnmanagedType.Bool)] bool fFullBuild
);
//------------------------------------------------------------------------------
private ISymUnmanagedWriterVTable m_vtable;
} // class SymWriter
- } //class SymWrapperCore
+ } // class SymWrapperCore
m_Release((IntPtr)0); // make one call to make sure the delegate is fully prepped before we're in the critical finalizer situation.
}
} // PunkSafeHandle
-} //namespace System.Reflection.Emit
+} // namespace System.Reflection.Emit
m_parameterTypeRequiredCustomModifiers = parameterTypeRequiredCustomModifiers;
m_parameterTypeOptionalCustomModifiers = parameterTypeOptionalCustomModifiers;
- // m_signature = SignatureHelper.GetMethodSigHelper(mod, callingConvention,
+ // m_signature = SignatureHelper.GetMethodSigHelper(mod, callingConvention,
// returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers,
// parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers);
m_mdMethodFixups = il.GetTokenFixups();
- //Okay, now the fun part. Calculate all of the exceptions.
+ // Okay, now the fun part. Calculate all of the exceptions.
excp = il.GetExceptions()!;
int numExceptions = CalculateNumberOfExceptions(excp);
if (numExceptions > 0)
// and namespace information with a given active lexical scope.
#region Internal Data Members
- internal string[] m_strName = null!; //All these arrys initialized in helper method
+ internal string[] m_strName = null!; // All these arrys initialized in helper method
internal byte[][] m_ubSignature = null!;
internal int[] m_iLocalSlot = null!;
internal int[] m_iStartOffset = null!;
{
type = RuntimeTypeHandle.GetCorElementType((RuntimeType)clsArgument);
- //GetCorElementType returns CorElementType.ELEMENT_TYPE_CLASS for both object and string
+ // GetCorElementType returns CorElementType.ELEMENT_TYPE_CLASS for both object and string
if (type == CorElementType.ELEMENT_TYPE_CLASS)
{
if (clsArgument == typeof(object))
// Pulls the token appart to get a rid, adds some appropriate bits
// to the token and then adds this to the signature.
- int rid = (token & 0x00FFFFFF); //This is RidFromToken;
- MetadataTokenType type = (MetadataTokenType)(token & unchecked((int)0xFF000000)); //This is TypeFromToken;
+ int rid = (token & 0x00FFFFFF); // This is RidFromToken;
+ MetadataTokenType type = (MetadataTokenType)(token & unchecked((int)0xFF000000)); // This is TypeFromToken;
if (rid > 0x3FFFFFF)
{
// TypeSpec is encoded with low bits 10
if (type == MetadataTokenType.TypeRef)
{
- //if type is mdtTypeRef
+ // if type is mdtTypeRef
rid |= 0x1;
}
else if (type == MetadataTokenType.TypeSpec)
{
- //if type is mdtTypeSpec
+ // if type is mdtTypeSpec
rid |= 0x2;
}
{
if (m_sizeLoc == NO_SIZE_IN_SIG)
{
- //We don't have a size if this is a field.
+ // We don't have a size if this is a field.
return;
}
if (m_sizeLoc == NO_SIZE_IN_SIG)
return;
- //If we have fewer than 128 arguments and we haven't been told to copy the
- //array, we can just set the appropriate bit and return.
+ // If we have fewer than 128 arguments and we haven't been told to copy the
+ // array, we can just set the appropriate bit and return.
if (m_argCount < 0x80 && !forceCopy)
{
m_signature[m_sizeLoc] = (byte)m_argCount;
return;
}
- //We need to have more bytes for the size. Figure out how many bytes here.
- //Since we need to copy anyway, we're just going to take the cost of doing a
- //new allocation.
+ // We need to have more bytes for the size. Figure out how many bytes here.
+ // Since we need to copy anyway, we're just going to take the cost of doing a
+ // new allocation.
if (m_argCount < 0x80)
{
newSigSize = 1;
newSigSize = 4;
}
- //Allocate the new array.
+ // Allocate the new array.
temp = new byte[m_currSig + newSigSize - 1];
- //Copy the calling convention. The calling convention is always just one byte
- //so we just copy that byte. Then copy the rest of the array, shifting everything
- //to make room for the new number of elements.
+ // Copy the calling convention. The calling convention is always just one byte
+ // so we just copy that byte. Then copy the rest of the array, shifting everything
+ // to make room for the new number of elements.
temp[0] = m_signature[0];
Buffer.BlockCopy(m_signature, m_sizeLoc + 1, temp, m_sizeLoc + newSigSize, currSigHolder - (m_sizeLoc + 1));
m_signature = temp;
- //Use the AddData method to add the number of elements appropriately compressed.
+ // Use the AddData method to add the number of elements appropriately compressed.
m_currSig = m_sizeLoc;
AddData(m_argCount);
m_currSig = currSigHolder + (newSigSize - 1);
int currSigLength = m_currSig;
int newSigSize = currSigLength;
- //Allocate the new array.
+ // Allocate the new array.
if (argCount < 0x7F)
newSigSize += 1;
else if (argCount < 0x3FFF)
if (destType.IsEnum)
{
- // | UnderlyingSystemType | Enum.GetUnderlyingType() | IsEnum
- // ----------------------------------|---------------------------|---------------------------|---------
- // runtime Enum Type | self | underlying type of enum | TRUE
- // EnumBuilder | underlying type of enum | underlying type of enum* | TRUE
- // TypeBuilder of enum types** | underlying type of enum | Exception | TRUE
- // TypeBuilder of enum types (baked) | runtime enum type | Exception | TRUE
-
- // *: the behavior of Enum.GetUnderlyingType(EnumBuilder) might change in the future
+ // | | UnderlyingSystemType | Enum.GetUnderlyingType() | IsEnum
+ // |-----------------------------------|---------------------------|---------------------------|---------
+ // | runtime Enum Type | self | underlying type of enum | TRUE
+ // | EnumBuilder | underlying type of enum | underlying type of enum* | TRUE
+ // | TypeBuilder of enum types** | underlying type of enum | Exception | TRUE
+ // | TypeBuilder of enum types (baked) | runtime enum type | Exception | TRUE
+
+ // *: the behavior of Enum.GetUnderlyingType(EnumBuilder) might change in the future
// so let's not depend on it.
// **: created with System.Enum as the parent type.
}
else if (type == typeof(DateTime))
{
- //date is a I8 representation
+ // date is a I8 representation
long ticks = ((DateTime)value).Ticks;
SetConstantValue(JitHelpers.GetQCallModuleOnStack(ref module), tk, (int)CorElementType.ELEMENT_TYPE_I8, &ticks);
}
if (!m_isHiddenGlobalType)
{
- //If this method is declared to be a constructor, increment our constructor count.
+ // If this method is declared to be a constructor, increment our constructor count.
if ((method.Attributes & MethodAttributes.SpecialName) != 0 && method.Name.Equals(ConstructorInfo.ConstructorName))
{
m_constructorCount++;
parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers,
m_module, this, false);
- //The signature grabbing code has to be up here or the signature won't be finished
- //and our equals check won't work.
+ // The signature grabbing code has to be up here or the signature won't be finished
+ // and our equals check won't work.
int sigLength;
byte[] sigBytes = method.GetMethodSignature().InternalGetSignature(out sigLength);
m_module,
name,
attributes,
- //tkType,
+ // tkType,
this,
evToken);
}
// We won't check on Interface because we can have class static initializer on interface.
// We will just let EE or validator to catch the problem.
- //((m_iAttr & TypeAttributes.ClassSemanticsMask) == TypeAttributes.Interface))
+ // ((m_iAttr & TypeAttributes.ClassSemanticsMask) == TypeAttributes.Interface))
if (body != null)
throw new InvalidOperationException(SR.Format(SR.InvalidOperation_BadMethodBody, meth.Name));
}
internal bool EqualsSig(RuntimePropertyInfo target)
{
- //@Asymmetry - Legacy policy is to remove duplicate properties, including hidden properties.
+ // @Asymmetry - Legacy policy is to remove duplicate properties, including hidden properties.
// The comparison is done by name and by sig. The EqualsSig comparison is expensive
// but forutnetly it is only called when an inherited property is hidden by name or
// when an interfaces declare properies with the same signature.
namespace System.Runtime.CompilerServices
{
- //=========================================================================================
+ // =========================================================================================
// This struct collects all operations on native DependentHandles. The DependentHandle
// merely wraps an IntPtr so this struct serves mainly as a "managed typedef."
//
//
// This struct intentionally does no self-synchronization. It's up to the caller to
// to use DependentHandles in a thread-safe way.
- //=========================================================================================
+ // =========================================================================================
internal struct DependentHandle
{
private IntPtr _handle;
return ReadValueSlow(ptr, ofs, (IntPtr nativeHome, int offset) => ReadInt64(nativeHome, offset));
}
- //====================================================================
- // Read value from marshaled object (marshaled using AsAny)
- // It's quite slow and can return back dangling pointers
- // It's only there for backcompact
- // People should instead use the IntPtr overloads
- //====================================================================
+ /// <summary>Read value from marshaled object (marshaled using AsAny).</summary>
+ /// <remarks>
+ /// It's quite slow and can return back dangling pointers. It's only there for backcompat.
+ /// People should instead use the IntPtr overloads.
+ /// </remarks>
private static unsafe T ReadValueSlow<T>(object ptr, int ofs, Func<IntPtr, int, T> readValueHelper)
{
// Consumers of this method are documented to throw AccessViolationException on any AV
namespace System
{
- // This value type is used for constructing System.ArgIterator.
+ // This value type is used for constructing System.ArgIterator.
//
// SECURITY : m_ptr cannot be set to anything other than null by untrusted
// code.
ExecutionContext.RunInternal(helper._executionContext, _ccb, helper);
}
- //Quickly check the VM again, to see if a packet has arrived.
+ // Quickly check the VM again, to see if a packet has arrived.
OverlappedData.CheckVMForIOPacket(out pNativeOverlapped, out errorCode, out numBytes);
} while (pNativeOverlapped != null);
}
internal static bool LoggingOn => f_LoggingOn != 0;
- //s_PlatformId = {4B0171A6-F3D0-41A0-9B33-02550652B995}
+ // s_PlatformId = {4B0171A6-F3D0-41A0-9B33-02550652B995}
private static readonly Guid s_PlatformId = new Guid(0x4B0171A6, 0xF3D0, 0x41A0, 0x9B, 0x33, 0x02, 0x55, 0x06, 0x52, 0xB9, 0x95);
- //Indicates this information comes from the BCL Library
+ // Indicates this information comes from the BCL Library
private const WFD.CausalitySource s_CausalitySource = WFD.CausalitySource.Library;
private static readonly WFD.IAsyncCausalityTracerStatics s_TracerFactory = null!;
}
- //We receive the actual value for these as a callback
- private static Loggers f_LoggingOn; //assumes false by default
+ // We receive the actual value for these as a callback
+ private static Loggers f_LoggingOn; // assumes false by default
// The precise static constructor will run first time somebody attempts to access this class
#pragma warning disable CA1810
{
if (!Environment.IsWinRTSupported) return;
- //COM Class Id
+ // COM Class Id
string ClassId = "Windows.Foundation.Diagnostics.AsyncCausalityTracer";
- //COM Interface GUID {50850B26-267E-451B-A890-AB6A370245EE}
+ // COM Interface GUID {50850B26-267E-451B-A890-AB6A370245EE}
Guid guid = new Guid(0x50850B26, 0x267E, 0x451B, 0xA8, 0x90, 0XAB, 0x6A, 0x37, 0x02, 0x45, 0xEE);
object? factory = null;
{
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.
+ if (hresult < 0 || factory == null) return; // This prevents having an exception thrown in case IAsyncCausalityTracerStatics isn't registered.
s_TracerFactory = (WFD.IAsyncCausalityTracerStatics)factory;
}
catch (Exception ex)
{
- //view function comment
+ // view function comment
LogAndDisable(ex);
}
}
}
catch (Exception ex)
{
- //view function comment
+ // view function comment
LogAndDisable(ex);
}
}
}
catch (Exception ex)
{
- //view function comment
+ // view function comment
LogAndDisable(ex);
}
}
}
catch (Exception ex)
{
- //view function comment
+ // view function comment
LogAndDisable(ex);
}
}
}
catch (Exception ex)
{
- //view function comment
+ // view function comment
LogAndDisable(ex);
}
}
- //fix for 796185: leaking internal exceptions to customers,
- //we should catch and log exceptions but never propagate them.
+ // fix for 796185: leaking internal exceptions to customers,
+ // we should catch and log exceptions but never propagate them.
private static void LogAndDisable(Exception ex)
{
f_LoggingOn = 0;
void TraceOperationRelation(CausalityTraceLevel traceLevel, CausalitySource source, Guid platformId, ulong operationId, CausalityRelation relation);
void TraceSynchronousWorkStart(CausalityTraceLevel traceLevel, CausalitySource source, Guid platformId, ulong operationId, CausalitySynchronousWork work);
void TraceSynchronousWorkCompletion(CausalityTraceLevel traceLevel, CausalitySource source, CausalitySynchronousWork work);
- //These next 2 functions could've been represented as an event except that the EventRegistrationToken wasn't being propagated to WinRT
+ // These next 2 functions could've been represented as an event except that the EventRegistrationToken wasn't being propagated to WinRT
EventRegistrationToken add_TracingStatusChanged(System.EventHandler<TracingStatusChangedEventArgs> eventHandler);
void remove_TracingStatusChanged(EventRegistrationToken token);
}
return __reftype(value).TypeHandle;
}
- // This may cause the type to be changed.
+ // This may cause the type to be changed.
[CLSCompliant(false)]
public static unsafe void SetTypedReference(TypedReference target, object? value)
{
{
internal struct Variant
{
- //Do Not change the order of these fields.
- //They are mapped to the native VariantData * data structure.
+ // Do Not change the order of these fields.
+ // They are mapped to the native VariantData * data structure.
private object? _objref;
private long _data;
private int _flags;
// bits 24-31 - Optional VT code (for roundtrip VT preservation)
- //What are the consequences of making this an enum?
+ // What are the consequences of making this an enum?
///////////////////////////////////////////////////////////////////////
// If you update this, update the corresponding stuff in OAVariantLib.cs,
// COMOAVariant.cpp (2 tables, forwards and reverse), and perhaps OleVariant.h
_flags |= ((int)vt << VTBitShift);
}
- //This is a family-only accessor for the CVType.
- //This is never to be exposed externally.
+ // This is a family-only accessor for the CVType.
+ // This is never to be exposed externally.
internal int CVType => (_flags & TypeCodeBitMask);
public object? ToObject()
throw new NotImplementedException();
}
- //Determines whether or not this instance of WeakReference still refers to an object
- //that has not been collected.
+ // Determines whether or not this instance of WeakReference still refers to an object
+ // that has not been collected.
//
public extern virtual bool IsAlive
{
get;
}
- //Returns a boolean indicating whether or not we're tracking objects until they're collected (true)
- //or just until they're finalized (false).
+ // Returns a boolean indicating whether or not we're tracking objects until they're collected (true)
+ // or just until they're finalized (false).
//
public virtual bool TrackResurrection => IsTrackResurrection();
- //Gets the Object stored in the handle if it's accessible.
+ // Gets the Object stored in the handle if it's accessible.
// Or sets it.
//
public extern virtual object? Target
public long GetLongLength(int dimension)
{
- //This method should throw an IndexOufOfRangeException for compat if dimension < 0 or >= Rank
+ // This method should throw an IndexOufOfRangeException for compat if dimension < 0 or >= Rank
return GetLength(dimension);
}
internal static readonly AttributeUsageAttribute Default = new AttributeUsageAttribute(AttributeTargets.All);
- //Constructors
public AttributeUsageAttribute(AttributeTargets validOn)
{
_attributeTarget = validOn;
// Determines whether two Boolean objects are equal.
public override bool Equals(object? obj)
{
- //If it's not a boolean, we're definitely not equal
+ // If it's not a boolean, we're definitely not equal
if (!(obj is bool))
{
return false;
// The commented out code below is code that directly implements the logic described above.
- //uint packedOriginalValues = (((uint)value & 0xF0U) << 4) + ((uint)value & 0x0FU);
- //uint difference = 0x8989U - packedOriginalValues;
- //uint add7Mask = (difference & 0x7070U) >> 4; // line YYY and ZZZ back up with the packed values
- //uint packedResult = packedOriginalValues + add7Mask + 0x3030U /* ascii '0' */;
+ // uint packedOriginalValues = (((uint)value & 0xF0U) << 4) + ((uint)value & 0x0FU);
+ // uint difference = 0x8989U - packedOriginalValues;
+ // uint add7Mask = (difference & 0x7070U) >> 4; // line YYY and ZZZ back up with the packed values
+ // uint packedResult = packedOriginalValues + add7Mask + 0x3030U /* ascii '0' */;
// The code below is equivalent to the commented out code above but has been tweaked
// to allow codegen to make some extra optimizations.
// CopyTo copies a collection into an Array, starting at a particular
// index into the array.
- //
void CopyTo(T[] array, int arrayIndex);
- //void CopyTo(int sourceIndex, T[] destinationArray, int destinationIndex, int count);
-
bool Remove(T item);
}
}
return prime;
}
- //outside of our predefined table.
- //compute the hard way.
+ // Outside of our predefined table. Compute the hard way.
for (int i = (min | 1); i < int.MaxValue; i += 2)
{
if (IsPrime(i) && ((i - 1) % HashPrime != 0))
protected Hashtable(SerializationInfo info, StreamingContext context)
{
- //We can't do anything with the keys and values until the entire graph has been deserialized
- //and we have a reasonable estimate that GetHashCode is not going to fail. For the time being,
- //we'll just cache this. The graph is not valid until OnDeserialization has been called.
+ // We can't do anything with the keys and values until the entire graph has been deserialized
+ // and we have a reasonable estimate that GetHashCode is not going to fail. For the time being,
+ // we'll just cache this. The graph is not valid until OnDeserialization has been called.
HashHelpers.SerializationInfoTable.Add(this, info);
}
{
int currentversion;
- // A read operation on hashtable has three steps:
+ // A read operation on hashtable has three steps:
// (1) calculate the hash and find the slot number.
// (2) compare the hashcode, if equal, go to step 3. Otherwise end.
// (3) compare the key, if equal, go to step 4. Otherwise end.
// that once contained an entry and also has had a collision.
// We need to search this entire collision chain because we have to ensure that there are no
// duplicate entries in the table.
- if (emptySlotNumber == -1 && (_buckets[bucketNumber].key == _buckets) && (_buckets[bucketNumber].hash_coll < 0))//(((buckets[bucketNumber].hash_coll & unchecked(0x80000000))!=0)))
+ if (emptySlotNumber == -1 && (_buckets[bucketNumber].key == _buckets) && (_buckets[bucketNumber].hash_coll < 0))// (((buckets[bucketNumber].hash_coll & unchecked(0x80000000))!=0)))
emptySlotNumber = bucketNumber;
// Insert the key/value pair into this bucket if this bucket is empty and has never contained an entry
}
#pragma warning restore 618
- info.AddValue(HashSizeName, _buckets.Length); //This is the length of the bucket array.
+ info.AddValue(HashSizeName, _buckets.Length); // This is the length of the bucket array.
object[] serKeys = new object[_count];
object[] serValues = new object[_count];
CopyKeys(serKeys, 0);
{
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, //62 is placed at index 43 (for +), 63 at index 47 (for /)
- 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, //52-61 are placed at index 48-57 (for 0-9), 64 at index 61 (for =)
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, // 62 is placed at index 43 (for +), 63 at index 47 (for /)
+ 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, // 52-61 are placed at index 48-57 (for 0-9), 64 at index 61 (for =)
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
- 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, //0-25 are placed at index 65-90 (for A-Z)
+ 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, // 0-25 are placed at index 65-90 (for A-Z)
-1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
- 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, //26-51 are placed at index 97-122 (for a-z)
+ 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, // 26-51 are placed at index 97-122 (for a-z)
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // Bytes over 122 ('z') are invalid and cannot be decoded
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // Hence, padding the map with 255, which indicates invalid input
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
public static partial class Convert
{
- //A typeof operation is fairly expensive (does a system call), so we'll cache these here
- //statically. These are exactly lined up with the TypeCode, eg. ConvertType[TypeCode.Int16]
- //will give you the type of an short.
+ // A typeof operation is fairly expensive (does a system call), so we'll cache these here
+ // statically. These are exactly lined up with the TypeCode, eg. ConvertType[TypeCode.Int16]
+ // will give you the type of an short.
internal static readonly Type[] ConvertTypes = {
typeof(System.Empty),
typeof(object),
typeof(double),
typeof(decimal),
typeof(DateTime),
- typeof(object), //TypeCode is discontinuous so we need a placeholder.
+ typeof(object), // TypeCode is discontinuous so we need a placeholder.
typeof(string)
};
return value.ToString(provider);
if (ReferenceEquals(targetType, ConvertTypes[(int)TypeCode.Object]))
return (object)value;
- // Need to special case Enum because typecode will be underlying type, e.g. Int32
+ // Need to special case Enum because typecode will be underlying type, e.g. Int32
if (ReferenceEquals(targetType, EnumType))
return (Enum)value;
if (ReferenceEquals(targetType, ConvertTypes[(int)TypeCode.DBNull]))
public static unsafe int ToBase64CharArray(byte[] inArray, int offsetIn, int length, char[] outArray, int offsetOut, Base64FormattingOptions options)
{
- //Do data verfication
+ // Do data verfication
if (inArray == null)
throw new ArgumentNullException(nameof(inArray));
if (outArray == null)
return 0;
bool insertLineBreaks = (options == Base64FormattingOptions.InsertLineBreaks);
- //This is the maximally required length that must be available in the char array
+ // This is the maximally required length that must be available in the char array
outArrayLength = outArray.Length;
// Length of the char buffer required
int calcLength = offset + (length - lengthmod3);
int j = 0;
int charcount = 0;
- //Convert three bytes at a time to base64 notation. This will consume 4 chars.
+ // Convert three bytes at a time to base64 notation. This will consume 4 chars.
int i;
// get a pointer to the base64Table to avoid unnecessary range checking
j += 4;
}
- //Where we left off before
+ // Where we left off before
i = calcLength;
if (insertLineBreaks && (lengthmod3 != 0) && (charcount == base64LineBreakPosition))
switch (lengthmod3)
{
- case 2: //One character padding needed
+ case 2: // One character padding needed
outChars[j] = base64[(inData[i] & 0xfc) >> 2];
outChars[j + 1] = base64[((inData[i] & 0x03) << 4) | ((inData[i + 1] & 0xf0) >> 4)];
outChars[j + 2] = base64[(inData[i + 1] & 0x0f) << 2];
- outChars[j + 3] = base64[64]; //Pad
+ outChars[j + 3] = base64[64]; // Pad
j += 4;
break;
case 1: // Two character padding needed
outChars[j] = base64[(inData[i] & 0xfc) >> 2];
outChars[j + 1] = base64[(inData[i] & 0x03) << 4];
- outChars[j + 2] = base64[64]; //Pad
- outChars[j + 3] = base64[64]; //Pad
+ outChars[j + 2] = base64[64]; // Pad
+ outChars[j + 3] = base64[64]; // Pad
j += 4;
break;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static long TimeToTicks(int hour, int minute, int second)
{
- //TimeSpan.TimeToTicks is a family access function which does no error checking, so
- //we need to put some error checking out here.
+ // TimeSpan.TimeToTicks is a family access function which does no error checking, so
+ // we need to put some error checking out here.
if ((uint)hour >= 24 || (uint)minute >= 60 || (uint)second >= 60)
{
ThrowHelper.ThrowArgumentOutOfRange_BadHourMinuteSecond();
private static unsafe uint GetExponent(float f)
{
// Based on pulling out the exp from this single struct layout
- //typedef struct {
+ // typedef struct {
// ULONG mant:23;
// ULONG exp:8;
// ULONG sign:1;
- //} SNGSTRUCT;
+ // } SNGSTRUCT;
return (byte)(*(uint*)&f >> 23);
}
private static unsafe uint GetExponent(double d)
{
// Based on pulling out the exp from this double struct layout
- //typedef struct {
+ // typedef struct {
// DWORDLONG mant:52;
// DWORDLONG signexp:12;
// } DBLSTRUCT;
Type c1, c2;
- // If a param array is present, then either
+ // If a param array is present, then either
// the user re-ordered the parameters in which case
// the argument to the param array is either an array
// in which case the params is conceptually ignored and so paramArrayType1 == null
namespace System.Diagnostics
{
- // DebuggerBrowsableState states are defined as follows:
- // Never element should never show
- // Expanded expansion of the class is done, so that all visible internal members are shown
- // Collapsed expansion of the class is not performed. Internal visible members are hidden
- // RootHidden The target element itself should not be shown, but should instead be
- // automatically expanded to have its members displayed.
- // Default value is collapsed
+ // DebuggerBrowsableState states are defined as follows:
+ // Never element should never show
+ // Expanded expansion of the class is done, so that all visible internal members are shown
+ // Collapsed expansion of the class is not performed. Internal visible members are hidden
+ // RootHidden The target element itself should not be shown, but should instead be
+ // automatically expanded to have its members displayed.
+ // Default value is collapsed
- // Please also change the code which validates DebuggerBrowsableState variable (in this file)
- // if you change this enum.
+ // Please also change the code which validates DebuggerBrowsableState variable (in this file)
+ // if you change this enum.
public enum DebuggerBrowsableState
{
Never = 0,
- //Expanded is not supported in this release
- //Expanded = 1,
+ // Expanded is not supported in this release
+ // Expanded = 1,
Collapsed = 2,
RootHidden = 3
}
[SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
public enum WriteEventErrorCode : int
{
- //check mapping to runtime codes
+ // check mapping to runtime codes
NoError = 0,
NoFreeBuffers = 1,
EventTooBig = 2,
this.m_Reserved = reserved; // Mark this descriptor as containing tracelogging-compatible metadata.
}
- //Important, we pass this structure directly to the Win32 EventWrite API, so this structure must be layed out exactly
- // the way EventWrite wants it.
+ // Important, we pass this structure directly to the Win32 EventWrite API, so this structure must
+ // be layed out exactly the way EventWrite wants it.
internal ulong m_Ptr;
internal int m_Size;
#pragma warning disable 0649
m_name = eventSourceName;
m_guid = eventSourceGuid;
- //Enable Implicit Activity tracker
+ // Enable Implicit Activity tracker
m_activityTracker = ActivityTracker.Instance;
#if FEATURE_MANAGED_ETW || FEATURE_PERFTRACING
// Everything else is marshaled as a string.
// ETW strings are NULL-terminated, so marshal everything up to the first
// null in the string.
- //return System.Runtime.InteropServices.Marshal.PtrToStringUni(dataPointer);
if (dataPointer == IntPtr.Zero)
{
return null;
return IsNaN(obj) && IsNaN(m_value);
}
- //The hashcode for a double is the absolute value of the integer representation
- //of that double.
- //
+ // The hashcode for a double is the absolute value of the integer representation
+ // of that double.
[MethodImpl(MethodImplOptions.AggressiveInlining)] // 64-bit constants make the IL unusually large that makes the inliner to reject the method
public override int GetHashCode()
{
internal override CalendarId ID => CalendarId.CHINESELUNISOLAR;
internal override CalendarId BaseCalendarID =>
- //Use CAL_GREGORIAN just to get CurrentEraValue as 1 since we do not have data under the ID CAL_ChineseLunisolar yet
+ // Use CAL_GREGORIAN just to get CurrentEraValue as 1 since we do not have data under the ID CAL_ChineseLunisolar yet
CalendarId.GREGORIAN;
public override int[] Eras => new int[] { ChineseEra };
/// </summary>
private static string GetTimeSeparator(string format)
{
- // Find the time separator so that we can pretend we know TimeSeparator.
+ // Find the time separator so that we can pretend we know TimeSeparator.
return GetSeparator(format, "Hhms");
}
/// </summary>
private static string GetDateSeparator(string format)
{
- // Find the date separator so that we can pretend we know DateSeparator.
+ // Find the date separator so that we can pretend we know DateSeparator.
return GetSeparator(format, "dyM");
}
case '\\':
break;
default:
- --i; //backup since we will move over this next
+ --i; // backup since we will move over this next
break;
}
}
// Get the current user default culture. This one is almost always used, so we create it by default.
private static volatile CultureInfo? s_userDefaultCulture;
- //The culture used in the user interface. This is mostly used to load correct localized resources.
+ // The culture used in the user interface. This is mostly used to load correct localized resources.
private static volatile CultureInfo? s_userDefaultUICulture;
// WARNING: We allow diagnostic tools to directly inspect these three members (s_InvariantCultureInfo, s_DefaultThreadCurrentUICulture and s_DefaultThreadCurrentCulture)
/// </summary>
public virtual string ThreeLetterWindowsLanguageName => _cultureData.ThreeLetterWindowsLanguageName;
- // CompareInfo Read-Only Property
/// <summary>
/// Gets the CompareInfo for this culture.
/// </summary>
*/
- //This class contains only static members and does not require the serializable attribute.
+ // This class contains only static members and does not require the serializable attribute.
internal static
class DateTimeFormat
{
int digits = (int)(buffer + 16 - p);
- //If the repeat count is greater than 0, we're trying
- //to emulate the "00" format, so we have to prepend
- //a zero if the string only has one character.
+ // If the repeat count is greater than 0, we're trying
+ // to emulate the "00" format, so we have to prepend
+ // a zero if the string only has one character.
while ((digits < len) && (p > buffer))
{
*--p = '0';
for (int i = 0; i < 7; i++)
{
- //String str = GetDayOfWeekNames()[i];
// We have to call public methods here to work with inherited DTFI.
string str = GetDayName((DayOfWeek)i);
InsertHash(temp, str, TokenType.DayOfWeekToken, i);
{
for (int i = 1; i <= 13; i++)
{
- //str = internalGetMonthName(i, MonthNameStyles.Regular, false);
// We have to call public methods here to work with inherited DTFI.
// Insert the month name first, so that they are at the front of abbreviated
// month names.
namespace System.Globalization
{
- //
// from LocaleEx.txt header
- //
- //; IFORMATFLAGS
- //; Parsing/formatting flags.
+ // IFORMATFLAGS
internal enum FORMATFLAGS
{
None = 0x00000000,
//
////////////////////////////////////////////////////////////////////////////
- // End NumEnd NumAmPm NumSpace NumDaySep NumTimesep MonthEnd MonthSpace MonthDSep NumDateSuff NumTimeSuff DayOfWeek YearSpace YearDateSep YearEnd TimeZone Era UTCTimeMark
+ // End NumEnd NumAmPm NumSpace NumDaySep NumTimesep MonthEnd MonthSpace MonthDSep NumDateSuff NumTimeSuff DayOfWeek YearSpace YearDateSep YearEnd TimeZone Era UTCTimeMark
private static readonly DS[][] dateParsingStates = {
// DS.BEGIN // DS.BEGIN
new DS[] { DS.BEGIN, DS.ERROR, DS.TX_N, DS.N, DS.D_Nd, DS.T_Nt, DS.ERROR, DS.D_M, DS.D_M, DS.D_S, DS.T_S, DS.BEGIN, DS.D_Y, DS.D_Y, DS.ERROR, DS.BEGIN, DS.BEGIN, DS.ERROR },
// DS.T_NNt // DS.T_NNt
new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.T_S, DS.T_NNt, DS.ERROR, DS.ERROR, DS.ERROR, DS.T_NNt, DS.T_NNt, DS.TX_NNN },
};
- // End NumEnd NumAmPm NumSpace NumDaySep NumTimesep MonthEnd MonthSpace MonthDSep NumDateSuff NumTimeSuff DayOfWeek YearSpace YearDateSep YearEnd TimeZone Era UTCMark
+ // End NumEnd NumAmPm NumSpace NumDaySep NumTimesep MonthEnd MonthSpace MonthDSep NumDateSuff NumTimeSuff DayOfWeek YearSpace YearDateSep YearEnd TimeZone Era UTCMark
internal const string GMTName = "GMT";
internal const string ZuluName = "Z";
}
break;
default:
- //Invalid separator after month name
+ // Invalid separator after month name
result.SetBadDateTimeFailure();
LexTraceExit("0130 (Invalid separator after month name)", dps);
return false;
{
if (result.Month == -1)
{
- //Should have a month suffix
+ // Should have a month suffix
result.SetBadDateTimeFailure();
return false;
}
int newLinePadding = 20;
- //invariant: strs.Length >= 2
+ // invariant: strs.Length >= 2
StringBuilder buffer = new StringBuilder();
buffer.Append(Hex(strs[0]));
curLineLength = buffer.Length;
AllowLeadingWhite = 0x00000001,
- AllowTrailingWhite = 0x00000002, //Bitflag indicating trailing whitespace is allowed.
+ AllowTrailingWhite = 0x00000002, // Bitflag indicating trailing whitespace is allowed.
AllowInnerWhite = 0x00000004,
// Will check the if the parameters are valid.
internal static long TimeToTicks(int hour, int minute, int second, int millisecond)
{
- //TimeSpan.TimeToTicks is a family access function which does no error checking, so
- //we need to put some error checking out here.
+ // TimeSpan.TimeToTicks is a family access function which does no error checking, so
+ // we need to put some error checking out here.
if (hour >= 0 && hour < 24 && minute >= 0 && minute < 60 && second >= 0 && second < 60)
{
if (millisecond < 0 || millisecond >= MillisPerSecond)
private const int DatePartMonth = 2;
private const int DatePartDay = 3;
- // Hebrew Translation Table.
+ // Hebrew Translation Table.
//
// This table is used to get the following Hebrew calendar information for a
// given Gregorian year:
private const int MaxMonthPlusOne = 14;
- // The lunar calendar has 6 different variations of month lengths
- // within a year.
+ // The lunar calendar has 6 different variations of month lengths
+ // within a year.
private static ReadOnlySpan<byte> LunarMonthLen => new byte[] // rely on C# compiler optimization to reference static data
{
0, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 0,
/// </returns>
internal static int GetLunarMonthDay(int gregorianYear, DateBuffer lunarDate)
{
- // Get the offset into the LunarMonthLen array and the lunar day
+ // Get the offset into the LunarMonthLen array and the lunar day
// for January 1st.
int index = gregorianYear - FirstGregorianTableYear;
if (index < 0 || index > TableSize)
// Get the type of the year. The value is from 1 to 6
int lunarYearType = HebrewTable[index + 1];
- // Get the Lunar Month.
+ // Get the Lunar Month.
switch (lunarDate.day)
{
case 0: // 1/1 is on Shvat 1
// This is the buffer used to store the result Hebrew date.
DateBuffer result = new DateBuffer();
- // Store the values for the start of the new year - 1/1.
+ // Store the values for the start of the new year - 1/1.
result.year = lunarDate.year;
result.month = lunarDate.month;
result.day = lunarDate.day;
- // Get the absolute date from 1/1/1600.
+ // Get the absolute date from 1/1/1600.
AbsoluteDate = GregorianCalendar.GetAbsoluteDate(gregorianYear, gregorianMonth, gregorianDay);
- // If the requested date was 1/1, then we're done.
+ // If the requested date was 1/1, then we're done.
if ((gregorianMonth == 1) && (gregorianDay == 1))
{
return GetResult(result, part);
// 1/1/0001 is absolute date 1.
long numDays = ticks / GregorianCalendar.TicksPerDay + 1;
- // See how much we need to backup or advance
+ // See how much we need to backup or advance
numDays += HijriAdjustment;
// Calculate the appromixate Hijri Year from this magic formula.
return hijriYear;
}
- // Calculate the Hijri Month.
+ // Calculate the Hijri Month.
int hijriMonth = 1;
numDays -= daysToHijriYear;
return hijriMonth;
}
- // Calculate the Hijri Day.
+ // Calculate the Hijri Day.
int hijriDay = (int)(numDays - s_hijriMonthDays[hijriMonth - 1]);
if (part == DatePartDay)
// 26-35 map to ASCII 0-9
if (d > 25) return (char)(d - 26 + '0');
- // 0-25 map to a-z or A-Z
+ // 0-25 map to a-z or A-Z
return (char)(d + 'a');
}
}
// 1/1/0001 is absolute date 1.
long numDays = ticks / GregorianCalendar.TicksPerDay + 1;
- // Calculate the appromixate Persian Year.
+ // Calculate the appromixate Persian Year.
long yearStart = CalendricalCalculationsHelper.PersianNewYearOnOrBefore(numDays);
int y = (int)(Math.Floor(((yearStart - s_persianEpoch) / CalendricalCalculationsHelper.MeanTropicalYearInDays) + 0.5)) + 1;
Debug.Assert(y >= 1);
return y;
}
- // Calculate the Persian Month.
+ // Calculate the Persian Month.
int ordinalDay = (int)(numDays - CalendricalCalculationsHelper.GetNumberOfDays(this.ToDateTime(y, 1, 1, 0, 0, 0, 0, 1)));
if (part == DatePartDayOfYear)
{
Debug.Assert(1 <= d);
Debug.Assert(d <= 31);
- // Calculate the Persian Day.
+ // Calculate the Persian Day.
if (part == DatePartDay)
{
return d;
{
// Standard Format Styles
None = 0x00000000,
- Invariant = 0x00000001, //Allow Invariant Culture
- Localized = 0x00000002, //Allow Localized Culture
- RequireFull = 0x00000004, //Require the input to be in DHMSF format
+ Invariant = 0x00000001, // Allow Invariant Culture
+ Localized = 0x00000002, // Allow Localized Culture
+ RequireFull = 0x00000004, // Require the input to be in DHMSF format
Any = Invariant | Localized,
}
{
short[] rawData = new short[]
{
- //These data is taken from Tables/Excel/UmAlQura.xls please make sure that the two places are in sync
+ // These data are taken from Tables/Excel/UmAlQura.xls please make sure that the two places are in sync
/* DaysPerM GY GM GD D1 D2 D3 D4 D5 D6 D7 D8 D9 D10 D11 D12
1318*/0x02EA, 1900, 4, 30, /* 0 1 0 1 0 1 1 1 0 1 0 0 4/30/1900
1319*/0x06E9, 1901, 4, 19, /* 1 0 0 1 0 1 1 1 0 1 1 0 4/19/1901
int index = (int)((time.Ticks - s_minDate.Ticks) / Calendar.TicksPerDay) / 355;
do
{
- } while (time.CompareTo(s_hijriYearInfo[++index].GregorianDate) > 0); //while greater
+ } while (time.CompareTo(s_hijriYearInfo[++index].GregorianDate) > 0); // while greater
if (time.CompareTo(s_hijriYearInfo[index].GregorianDate) != 0)
{
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-//=============================================================================
+// =============================================================================
//
//
// Purpose: Define HResult constants. Every exception has one of these.
//
//
-//===========================================================================*/
+// ===========================================================================*/
// Note: FACILITY_URT is defined as 0x13 (0x8013xxxx). Within that
// range, 0x1yyy is for Runtime errors (used for Security, Metadata, etc).
// In that subrange, 0x15zz and 0x16zz have been allocated for classlib-type
if (_charBytes == null)
{
- _charBytes = new byte[MaxCharBytesSize]; //REVIEW: We need at most 2 bytes/char here?
+ _charBytes = new byte[MaxCharBytesSize];
}
Span<char> singleChar = stackalloc char[1];
if (len <= _largeByteBuffer.Length)
{
- //Debug.Assert(len == _encoding.GetBytes(chars, 0, chars.Length, _largeByteBuffer, 0), "encoding's GetByteCount & GetBytes gave different answers! encoding type: "+_encoding.GetType().Name);
_encoding.GetBytes(value, 0, value.Length, _largeByteBuffer, 0);
OutStream.Write(_largeByteBuffer, 0, len);
}
{
_bytesRead = bytesRead;
_stateObject = asyncStateObject;
- //_isWrite = false;
}
internal SynchronousAsyncResult(object? asyncStateObject)
_charLen += _decoder.GetChars(_byteBuffer, 0, _byteLen, _charBuffer, _charLen);
} while (_charLen == 0);
- //Console.WriteLine("ReadBuffer called. chars: "+charLen);
return _charLen;
}
_isBlocked &= charsRead < userBuffer.Length;
- //Console.WriteLine("ReadBuffer: charsRead: "+charsRead+" readToUserBuffer: "+readToUserBuffer);
return charsRead;
}
/// to ensure that the Lazy<T> does not become initialized if it was not already.</summary>
internal sealed class LazyDebugView<T>
{
- //The Lazy object being viewed.
+ // The Lazy object being viewed.
private readonly Lazy<T> _lazy;
/// <summary>Constructs a new debugger view object for the provided Lazy object.</summary>
**
===========================================================*/
-//This class contains only static members and doesn't require serialization.
-
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
**
===========================================================*/
-//This class contains only static members and doesn't require serialization.
-
using System.Diagnostics;
using System.Runtime.CompilerServices;
{
internal static partial class Number
{
- // We need 1 additional byte, per length, for the terminating null
+ // We need 1 additional byte, per length, for the terminating null
internal const int DecimalNumberBufferLength = 29 + 1 + 1; // 29 for the longest input + 1 for rounding
internal const int DoubleNumberBufferLength = 767 + 1 + 1; // 767 for the longest input + 1 for rounding: 4.9406564584124654E-324
internal const int Int32NumberBufferLength = 10 + 1; // 10 for the longest input: 2,147,483,647
if ((flags & IsTight) != 0)
{
- //If we've got effluvia left at the end of the string, complain.
+ // If we've got effluvia left at the end of the string, complain.
if (i < length)
throw new FormatException(SR.Format_ExtraJunkAtEnd);
}
if (radix < MinRadix || radix > MaxRadix)
throw new ArgumentException(SR.Arg_InvalidBase, nameof(radix));
- //If the number is negative, make it positive and remember the sign.
+ // If the number is negative, make it positive and remember the sign.
ulong ul;
bool isNegative = false;
if (n < 0)
ul &= 0xFFFFFFFF;
}
- //Special case the 0.
+ // Special case the 0.
int index;
if (0 == ul)
{
Debug.Assert(ul == 0, $"Expected {ul} == 0");
}
- //If they want the base, append that to the string (in reverse order)
+ // If they want the base, append that to the string (in reverse order)
if (radix != 10 && ((flags & PrintBase) != 0))
{
if (16 == radix)
if (10 == radix)
{
- //If it was negative, append the sign.
+ // If it was negative, append the sign.
if (isNegative)
{
buffer[index++] = '-';
}
- //else if they requested, add the '+';
+ // else if they requested, add the '+';
else if ((flags & PrintSign) != 0)
{
buffer[index++] = '+';
}
- //If they requested a leading space, put it on.
+ // If they requested a leading space, put it on.
else if ((flags & PrefixSpace) != 0)
{
buffer[index++] = ' ';
int ii = 0;
int mj, mk;
- //Initialize our Seed array.
+ // Initialize our Seed array.
int subtraction = (Seed == int.MinValue) ? int.MaxValue : Math.Abs(Seed);
mj = MSEED - subtraction;
_seedArray[55] = mj;
mk = 1;
for (int i = 1; i < 55; i++)
- { //Apparently the range [1..55] is special (Knuth) and so we're wasting the 0'th position.
+ { // Apparently the range [1..55] is special (Knuth) and so we're wasting the 0'th position.
if ((ii += 21) >= 55) ii -= 55;
_seedArray[ii] = mk;
mk = mj - mk;
==============================================================================*/
protected virtual double Sample()
{
- //Including this division at the end gives us significantly improved
- //random number distribution.
+ // Including this division at the end gives us significantly improved
+ // random number distribution.
return (InternalSample() * (1.0 / MBIG));
}
return (RFC3986UnreservedMarks.Contains(c));
}
- //Only consider ASCII characters
+ // Only consider ASCII characters
internal static bool IsAsciiLetter(char character)
{
return (character >= 'a' && character <= 'z') ||
private static readonly char[] s_hexUpperChars = {
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
- internal const char c_DummyChar = (char)0xFFFF; //An Invalid Unicode character used as a dummy char passed into the parameter
+ internal const char c_DummyChar = (char)0xFFFF; // An Invalid Unicode character used as a dummy char passed into the parameter
private const short c_MaxAsciiCharsReallocate = 40;
private const short c_MaxUnicodeCharsReallocate = 40;
private const short c_MaxUTF_8BytesPerUnicodeChar = 4;
// Flag used to indicate that an assembly ref contains the full public key, not the compressed token.
// Must match afPublicKey in CorHdr.h.
PublicKey = 0x0001,
- //ProcArchMask = 0x00F0, // Bits describing the processor architecture
+ // ProcArchMask = 0x00F0, // Bits describing the processor architecture
// Accessible via AssemblyName.ProcessorArchitecture
EnableJITcompileOptimizer = 0x4000,
EnableJITcompileTracking = 0x8000,
Retargetable = 0x0100,
- //ContentType = 0x0E00, // Bits describing the ContentType are accessible via AssemblyName.ContentType
+ // ContentType = 0x0E00, // Bits describing the ContentType are accessible via AssemblyName.ContentType
}
}
bool needsQuoting = false;
const char quoteChar = '\"';
- //@todo: App-compat: You can use double or single quotes to quote a name, and Fusion (or rather the IdentityAuthority) picks one
- // by some algorithm. Rather than guess at it, I'll just use double-quote consistently.
+ // App-compat: You can use double or single quotes to quote a name, and Fusion (or rather the IdentityAuthority) picks one
+ // by some algorithm. Rather than guess at it, we use double quotes consistently.
if (s != s.Trim() || s.Contains('\"') || s.Contains('\''))
needsQuoting = true;
[Flags]
public enum CallingConventions
{
- //NOTE: If you change this please update COMMember.cpp. These
- // are defined there.
+ // Keep in sync with COMMember.cpp.
Standard = 0x0001,
VarArgs = 0x0002,
Any = Standard | VarArgs,
{
internal readonly int m_label;
- //public Label() {
- // m_label=0;
- //}
-
internal Label(int label)
{
m_label = label;
public virtual IEnumerable<Type> ImplementedInterfaces => GetInterfaces();
- //a re-implementation of ISAF from Type, skipping the use of UnderlyingType
+ // a re-implementation of ISAF from Type, skipping the use of UnderlyingType
public virtual bool IsAssignableFrom(TypeInfo? typeInfo)
{
if (typeInfo == null)
// 5) ResourceSet type name for this file (bytelength-prefixed UTF8 String)
public static readonly int HeaderVersionNumber = 1;
- //
- //It would be better if we could use _neutralCulture instead of calling
- //CultureInfo.InvariantCulture everywhere, but we run into problems with the .cctor. CultureInfo
- //initializes assembly, which initializes ResourceManager, which tries to get a CultureInfo which isn't
- //there yet because CultureInfo's class initializer hasn't finished. If we move SystemResMgr off of
- //Assembly (or at least make it an internal property) we should be able to circumvent this problem.
- //
- // private static CultureInfo _neutralCulture = null;
+ // It would be better if we could use a _neutralCulture instead of calling
+ // CultureInfo.InvariantCulture everywhere, but we run into problems with the .cctor. CultureInfo
+ // initializes assembly, which initializes ResourceManager, which tries to get a CultureInfo which isn't
+ // there yet because CultureInfo's class initializer hasn't finished. If we move SystemResMgr off of
+ // Assembly (or at least make it an internal property) we should be able to circumvent this problem.
// This is our min required ResourceSet type.
private static readonly Type s_minResourceSet = typeof(ResourceSet);
// On 64-bit machines, these char*'s may be misaligned. Use a
// byte-by-byte comparison instead.
- //return FastResourceComparer.CompareOrdinal((char*)bytes, byteLen/2, name) == 0;
return FastResourceComparer.CompareOrdinal(bytes, byteLen, name) == 0;
}
else
[StructLayout(LayoutKind.Sequential)]
public struct FUNCDESC
{
- public int memid; //MEMBERID memid;
+ public int memid; // MEMBERID memid;
public IntPtr lprgscode; // /* [size_is(cScodes)] */ SCODE RPC_FAR *lprgscode;
public IntPtr lprgelemdescParam; // /* [size_is(cParams)] */ ELEMDESC __RPC_FAR *lprgelemdescParam;
- public FUNCKIND funckind; //FUNCKIND funckind;
- public INVOKEKIND invkind; //INVOKEKIND invkind;
- public CALLCONV callconv; //CALLCONV callconv;
- public short cParams; //short cParams;
- public short cParamsOpt; //short cParamsOpt;
- public short oVft; //short oVft;
- public short cScodes; //short cScodes;
- public ELEMDESC elemdescFunc; //ELEMDESC elemdescFunc;
- public short wFuncFlags; //WORD wFuncFlags;
+ public FUNCKIND funckind; // FUNCKIND funckind;
+ public INVOKEKIND invkind; // INVOKEKIND invkind;
+ public CALLCONV callconv; // CALLCONV callconv;
+ public short cParams; // short cParams;
+ public short cParamsOpt; // short cParamsOpt;
+ public short oVft; // short oVft;
+ public short cScodes; // short cScodes;
+ public ELEMDESC elemdescFunc; // ELEMDESC elemdescFunc;
+ public short wFuncFlags; // WORD wFuncFlags;
}
[Flags]
// This function needs to return the HMODULE of the dll it loads
protected virtual IntPtr LoadUnmanagedDll(string unmanagedDllName)
{
- //defer to default coreclr policy of loading unmanaged dll
+ // defer to default coreclr policy of loading unmanaged dll
return IntPtr.Zero;
}
throw new InsufficientMemoryException(SR.InsufficientMemory_MemFailPoint_TooBig);
ulong requestedSizeRounded = (ulong)(Math.Ceiling((double)sizeInMegabytes / MemoryCheckGranularity) * MemoryCheckGranularity);
- //re-convert into bytes
+ // re-convert into bytes
requestedSizeRounded <<= 20;
ulong availPageFile = 0; // available VM (physical + page file)
_data = info;
_types = types;
- //The MoveNext semantic is much easier if we enforce that [0..m_numItems] are valid entries
- //in the enumerator, hence we subtract 1.
+ // The MoveNext semantic is much easier if we enforce that [0..m_numItems] are valid entries
+ // in the enumerator, hence we subtract 1.
_numItems = numItems - 1;
_currItem = -1;
_current = false;
{
int copyLength = Length - remainingLength;
- //Copy the characters already proven not to match.
+ // Copy the characters already proven not to match.
if (copyLength > 0)
{
wstrcpy(pResult, pChars, copyLength);
}
- //Copy the remaining characters, doing the replacement as we go.
+ // Copy the remaining characters, doing the replacement as we go.
char* pSrc = pChars + copyLength;
char* pDst = pResult + copyLength;
count--;
int numActualReplaces = (sepList.Length < count) ? sepList.Length : count;
- //Allocate space for the new array.
- //+1 for the string from the end of the last replace to the end of the string.
+ // Allocate space for the new array.
+ // +1 for the string from the end of the last replace to the end of the string.
string[] splitStrings = new string[numActualReplaces + 1];
for (int i = 0; i < numActualReplaces && currIndex < Length; i++)
currIndex = sepList[i] + (lengthList.IsEmpty ? defaultLength : lengthList[i]);
}
- //Handle the last string at the end of the array if there is one.
+ // Handle the last string at the end of the array if there is one.
if (currIndex < Length && numActualReplaces >= 0)
{
splitStrings[arrIndex] = Substring(currIndex);
}
else if (arrIndex == numActualReplaces)
{
- //We had a separator character at the end of a string. Rather than just allowing
- //a null character, we'll replace the last element in the array with an empty string.
+ // We had a separator character at the end of a string. Rather than just allowing
+ // a null character, we'll replace the last element in the array with an empty string.
splitStrings[arrIndex] = string.Empty;
}
// we must have at least one slot left to fill in the last string.
Debug.Assert(arrIndex < maxItems);
- //Handle the last string at the end of the array if there is one.
+ // Handle the last string at the end of the array if there is one.
if (currIndex < Length)
{
splitStrings[arrIndex++] = Substring(currIndex);
return cult.TextInfo.ToUpper(this);
}
- //Creates a copy of this string in upper case based on invariant culture.
+ // Creates a copy of this string in upper case based on invariant culture.
public string ToUpperInvariant()
{
return CultureInfo.InvariantCulture.TextInfo.ToUpper(this);
private const uint MIMECONTF_SAVABLE_MAILNEWS = Encoding.MIMECONTF_SAVABLE_MAILNEWS;
private const uint MIMECONTF_SAVABLE_BROWSER = Encoding.MIMECONTF_SAVABLE_BROWSER;
- //
- //s_flags is indexed by the corresponding index in s_mappedCodePages.
- //
+ // s_flags is indexed by the corresponding index in s_mappedCodePages.
private static readonly uint[] s_flags = new uint[]
{
MIMECONTF_SAVABLE_BROWSER,
ReadOnlySpan<char> invariantName = name.ToLowerInvariant().AsSpan();
- //Binary search the array until we have only a couple of elements left and then
- //just walk those elements.
+ // Binary search the array until we have only a couple of elements left and then
+ // just walk those elements.
while ((right - left) > 3)
{
index = ((right - left) / 2) + left;
if (result == 0)
{
- //We found the item, return the associated codePage.
+ // We found the item, return the associated codePage.
return s_codePagesByName[index];
}
else if (result < 0)
{
- //The name that we're looking for is less than our current index.
+ // The name that we're looking for is less than our current index.
right = index;
}
else
{
- //The name that we're looking for is greater than our current index
+ // The name that we're looking for is greater than our current index
left = index;
}
}
- //Walk the remaining elements (it'll be 3 or fewer).
+ // Walk the remaining elements (it'll be 3 or fewer).
for (; left <= right; left++)
{
Debug.Assert(left < s_encodingNameIndices.Length - 1);
}
set
{
- //If the new length is less than 0 or greater than our Maximum capacity, bail.
+ // If the new length is less than 0 or greater than our Maximum capacity, bail.
if (value < 0)
{
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NegativeLength);
public override int GetHashCode()
{
- //Not great distribution, but this is relatively unlikely to be used as the key in a hashtable.
+ // Not great distribution, but this is relatively unlikely to be used as the key in a hashtable.
return this.EncoderFallback.GetHashCode() + this.DecoderFallback.GetHashCode() +
CodePage + (_emitUTF32ByteOrderMark ? 4 : 0) + (_bigEndian ? 8 : 0);
}
{
private const string base64Chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
- // 0123456789111111111122222222223333333333444444444455555555556666
- // 012345678901234567890123456789012345678901234567890123
+ // 0123456789111111111122222222223333333333444444444455555555556666
+ // 012345678901234567890123456789012345678901234567890123
// These are the characters that can be directly encoded in UTF7.
private const string directChars =
}
public UTF7Encoding(bool allowOptionals)
- : base(UTF7_CODEPAGE) //Set the data item.
+ : base(UTF7_CODEPAGE) // Set the data item.
{
// Allowing optionals?
_allowOptionals = allowOptionals;
public override int GetHashCode()
{
- //Not great distribution, but this is relatively unlikely to be used as the key in a hashtable.
+ // Not great distribution, but this is relatively unlikely to be used as the key in a hashtable.
return this.EncoderFallback.GetHashCode() + this.DecoderFallback.GetHashCode() +
UTF8_CODEPAGE + (_emitUTF8Identifier ? 1 : 0);
}
goto Error; // this is an overlong encoding; fail
}
- partialChar -= ((0xEDu - 0xC2u) << 12) + (0xA0u << 6); //if partialChar = 0, we're at beginning of UTF-16 surrogate code point range
+ partialChar -= ((0xEDu - 0xC2u) << 12) + (0xA0u << 6); // if partialChar = 0, we're at beginning of UTF-16 surrogate code point range
if (partialChar < (0x0800u /* number of code points in UTF-16 surrogate code point range */))
{
goto Error; // attempted to encode a UTF-16 surrogate code point; fail
{
if (Rune.DecodeFromUtf8(valueAsBytes, out _, out int bytesConsumed) == OperationStatus.Done)
{
- // Valid scalar value - copy data as-is to MemoryStream
+ // Valid scalar value - copy data as-is to MemoryStream
memStream.Write(valueAsBytes.Slice(0, bytesConsumed));
}
else
public UnicodeEncoding(bool bigEndian, bool byteOrderMark)
- : base(bigEndian ? 1201 : 1200) //Set the data item.
+ : base(bigEndian ? 1201 : 1200) // Set the data item.
{
this.bigEndian = bigEndian;
this.byteOrderMark = byteOrderMark;
{
Debug.Assert((decoder.MustFlush == false) || ((lastChar == (char)0) && (lastByte == -1)),
"[UnicodeEncoding.GetChars] Expected no left over chars or bytes if flushing"
- // + " " + ((int)lastChar).ToString("X4") + " " + lastByte.ToString("X2")
+ // + " " + ((int)lastChar).ToString("X4") + " " + lastByte.ToString("X2")
);
decoder._bytesUsed = (int)(bytes - byteStart);
//
return (CodePage == that.CodePage) &&
byteOrderMark == that.byteOrderMark &&
- // isThrowException == that.isThrowException && // Same as Encoder/Decoder being exception fallbacks
+ // isThrowException == that.isThrowException && // Same as Encoder/Decoder being exception fallbacks
bigEndian == that.bigEndian &&
(EncoderFallback.Equals(that.EncoderFallback)) &&
(DecoderFallback.Equals(that.DecoderFallback));
// if null, it implicitly represents the same thing as new CancellationToken(false).
// When required, it will be instantiated to reflect this.
private readonly CancellationTokenSource? _source;
- //!! warning. If more fields are added, the assumptions in CreateLinkedToken may no longer be valid
+ // !! warning. If more fields are added, the assumptions in CreateLinkedToken may no longer be valid
private static readonly Action<object?> s_actionToActionObjShunt = obj =>
{
private volatile ManualResetEvent? m_eventObj; // A true Win32 event used for waiting.
// -- State -- //
- //For a packed word a uint would seem better, but Interlocked.* doesn't support them as uint isn't CLS-compliant.
- private volatile int m_combinedState; //ie a uint. Used for the state items listed below.
+ // For a packed word a uint would seem better, but Interlocked.* doesn't support them as uint isn't CLS-compliant.
+ private volatile int m_combinedState; // ie a uint. Used for the state items listed below.
- //1-bit for signalled state
- private const int SignalledState_BitMask = unchecked((int)0x80000000); //1000 0000 0000 0000 0000 0000 0000 0000
+ // 1-bit for signalled state
+ private const int SignalledState_BitMask = unchecked((int)0x80000000); // 1000 0000 0000 0000 0000 0000 0000 0000
private const int SignalledState_ShiftCount = 31;
- //1-bit for disposed state
- private const int Dispose_BitMask = unchecked((int)0x40000000); //0100 0000 0000 0000 0000 0000 0000 0000
+ // 1-bit for disposed state
+ private const int Dispose_BitMask = unchecked((int)0x40000000); // 0100 0000 0000 0000 0000 0000 0000 0000
- //11-bits for m_spinCount
- private const int SpinCountState_BitMask = unchecked((int)0x3FF80000); //0011 1111 1111 1000 0000 0000 0000 0000
+ // 11-bits for m_spinCount
+ private const int SpinCountState_BitMask = unchecked((int)0x3FF80000); // 0011 1111 1111 1000 0000 0000 0000 0000
private const int SpinCountState_ShiftCount = 19;
- private const int SpinCountState_MaxValue = (1 << 11) - 1; //2047
+ private const int SpinCountState_MaxValue = (1 << 11) - 1; // 2047
- //19-bits for m_waiters. This allows support of 512K threads waiting which should be ample
+ // 19-bits for m_waiters. This allows support of 512K threads waiting which should be ample
private const int NumWaitersState_BitMask = unchecked((int)0x0007FFFF); // 0000 0000 0000 0111 1111 1111 1111 1111
private const int NumWaitersState_ShiftCount = 0;
- private const int NumWaitersState_MaxValue = (1 << 19) - 1; //512K-1
+ private const int NumWaitersState_MaxValue = (1 << 19) - 1; // 512K-1
// ----------- //
/// <summary>
set
{
- //setting to <0 would indicate an internal flaw, hence Assert is appropriate.
+ // setting to <0 would indicate an internal flaw, hence Assert is appropriate.
Debug.Assert(value >= 0, "NumWaiters should never be less than zero. This indicates an internal error.");
// it is possible for the max number of waiters to be exceeded via user-code, hence we use a real exception here.
private void Initialize(bool initialState, int spinCount)
{
m_combinedState = initialState ? (1 << SignalledState_ShiftCount) : 0;
- //the spinCount argument has been validated by the ctors.
- //but we now sanity check our predefined constants.
+ // 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.");
// If there are waiting threads, we need to pulse them.
if (Waiters > 0)
{
- Debug.Assert(m_lock != null); //if waiters>0, then m_lock has already been created.
+ Debug.Assert(m_lock != null); // if waiters>0, then m_lock has already been created.
lock (m_lock)
{
Monitor.PulseAll(m_lock);
ManualResetEvent? eventObj = m_eventObj;
- //Design-decision: do not set the event if we are in cancellation -> better to deadlock than to wake up waiters incorrectly
- //It would be preferable to wake up the event and have it throw OCE. This requires MRE to implement cancellation logic
+ // Design-decision: do not set the event if we are in cancellation -> better to deadlock than to wake up waiters incorrectly
+ // It would be preferable to wake up the event and have it throw OCE. This requires MRE to implement cancellation logic
if (eventObj != null && !duringCancellation)
{
// We spin briefly before falling back to allocating and/or waiting on a true event.
uint startTime = 0;
bool bNeedTimeoutAdjustment = false;
- int realMillisecondsTimeout = millisecondsTimeout; //this will be adjusted if necessary.
+ int realMillisecondsTimeout = millisecondsTimeout; // this will be adjusted if necessary.
if (millisecondsTimeout != Timeout.Infinite)
{
// If our token was canceled, we must throw and exit.
cancellationToken.ThrowIfCancellationRequested();
- //update timeout (delays in wait commencement are due to spinning and/or spurious wakeups from other waits being canceled)
+ // update timeout (delays in wait commencement are due to spinning and/or spurious wakeups from other waits being canceled)
if (bNeedTimeoutAdjustment)
{
realMillisecondsTimeout = TimeoutHelper.UpdateTimeOut(startTime, millisecondsTimeout);
Waiters++;
- if (IsSet) //This check must occur after updating Waiters.
+ if (IsSet) // This check must occur after updating Waiters.
{
- Waiters--; //revert the increment.
+ Waiters--; // revert the increment.
return true;
}
{
// ** the actual wait **
if (!Monitor.Wait(m_lock, realMillisecondsTimeout))
- return false; //return immediately if the timeout has expired.
+ return false; // return immediately if the timeout has expired.
}
finally
{
}
} // automatically disposes (and unregisters) the callback
- return true; //done. The wait was satisfied.
+ return true; // done. The wait was satisfied.
}
/// <summary>
if ((m_combinedState & Dispose_BitMask) != 0)
return; // already disposed
- m_combinedState |= Dispose_BitMask; //set the dispose bit
+ m_combinedState |= Dispose_BitMask; // set the dispose bit
if (disposing)
{
// We will dispose of the event object. We do this under a lock to protect
{
Debug.Assert(obj is ManualResetEventSlim, "Expected a ManualResetEventSlim");
ManualResetEventSlim mre = (ManualResetEventSlim)obj;
- Debug.Assert(mre.m_lock != null); //the lock should have been created before this callback is registered for use.
+ Debug.Assert(mre.m_lock != null); // the lock should have been created before this callback is registered for use.
lock (mre.m_lock)
{
Monitor.PulseAll(mre.m_lock); // awaken all waiters
/// <returns></returns>
private static int ExtractStatePortionAndShiftRight(int state, int mask, int rightBitShiftCount)
{
- //convert to uint before shifting so that right-shift does not replicate the sign-bit,
- //then convert back to int.
+ // convert to uint before shifting so that right-shift does not replicate the sign-bit,
+ // then convert back to int.
return unchecked((int)(((uint)(state & mask)) >> rightBitShiftCount));
}
{
private static readonly int ProcessorCount = Environment.ProcessorCount;
- //Specifying if the lock can be reacquired recursively.
+ // Specifying if the lock can be reacquired recursively.
private readonly bool _fIsReentrant;
// Lock specification for _spinLock: This lock protects exactly the local fields associated with this
private const int MaxSpinCount = 20;
- //The uint, that contains info like if the writer lock is held, num of
- //readers etc.
+ // The uint, that contains info like if the writer lock is held, num of
+ // readers etc.
private uint _owners;
- //Various R/W masks
- //Note:
- //The Uint is divided as follows:
+ // Various R/W masks
+ // Note:
+ // The Uint is divided as follows:
//
- //Writer-Owned Waiting-Writers Waiting Upgraders Num-Readers
+ // Writer-Owned Waiting-Writers Waiting Upgraders Num-Readers
// 31 30 29 28.......0
//
- //Dividing the uint, allows to vastly simplify logic for checking if a
- //reader should go in etc. Setting the writer bit will automatically
- //make the value of the uint much larger than the max num of readers
- //allowed, thus causing the check for max_readers to fail.
+ // Dividing the uint, allows to vastly simplify logic for checking if a
+ // reader should go in etc. Setting the writer bit will automatically
+ // make the value of the uint much larger than the max num of readers
+ // allowed, thus causing the check for max_readers to fail.
private const uint WRITER_HELD = 0x80000000;
private const uint WAITING_WRITERS = 0x40000000;
private const uint WAITING_UPGRADER = 0x20000000;
- //The max readers is actually one less then its theoretical max.
- //This is done in order to prevent reader count overflows. If the reader
- //count reaches max, other readers will wait.
+ // The max readers is actually one less then its theoretical max.
+ // This is done in order to prevent reader count overflows. If the reader
+ // count reaches max, other readers will wait.
private const uint MAX_READER = 0x10000000 - 2;
private const uint READER_MASK = 0x10000000 - 1;
{
if (id == _writeLockOwnerId)
{
- //Check for AW->AR
+ // Check for AW->AR
throw new LockRecursionException(SR.LockRecursionException_ReadAfterWriteNotAllowed);
}
lrwc = GetThreadRWCount(dontAllocate: false)!;
- //Check if the reader lock is already acquired. Note, we could
- //check the presence of a reader by not allocating rwc (But that
- //would lead to two lookups in the common case. It's better to keep
- //a count in the structure).
+ // Check if the reader lock is already acquired. Note, we could
+ // check the presence of a reader by not allocating rwc (But that
+ // would lead to two lookups in the common case. It's better to keep
+ // a count in the structure).
if (lrwc.readercount > 0)
{
_spinLock.Exit();
}
else if (id == _upgradeLockOwnerId)
{
- //The upgrade lock is already held.
- //Update the global read counts and exit.
+ // The upgrade lock is already held.
+ // Update the global read counts and exit.
lrwc.readercount++;
_owners++;
}
else if (id == _upgradeLockOwnerId)
{
- //The upgrade lock is already held.
- //Update the global read counts and exit.
+ // The upgrade lock is already held.
+ // Update the global read counts and exit.
lrwc.readercount++;
_owners++;
_spinLock.Exit();
}
else if (id == _writeLockOwnerId)
{
- //The write lock is already held.
- //Update global read counts here,
+ // The write lock is already held.
+ // Update global read counts here,
lrwc.readercount++;
_owners++;
_spinLock.Exit();
spinCount++;
SpinWait(spinCount);
_spinLock.Enter(EnterSpinLockReason.EnterAnyRead);
- //The per-thread structure may have been recycled as the lock is acquired (due to message pumping), load again.
+ // The per-thread structure may have been recycled as the lock is acquired (due to message pumping), load again.
if (IsRwHashEntryChanged(lrwc))
lrwc = GetThreadRWCount(dontAllocate: false)!;
continue;
EnterSpinLockReason enterMyLockReason;
if (id == _writeLockOwnerId)
{
- //Check for AW->AW
+ // Check for AW->AW
throw new LockRecursionException(SR.LockRecursionException_RecursiveWriteNotAllowed);
}
else if (id == _upgradeLockOwnerId)
{
- //AU->AW case is allowed once.
+ // AU->AW case is allowed once.
upgradingToWrite = true;
enterMyLockReason = EnterSpinLockReason.UpgradeToWrite;
}
lrwc = GetThreadRWCount(dontAllocate: true);
- //Can't acquire write lock with reader lock held.
+ // Can't acquire write lock with reader lock held.
if (lrwc != null && lrwc.readercount > 0)
{
_spinLock.Exit();
}
else if (lrwc.readercount > 0)
{
- //Write locks may not be acquired if only read locks have been
- //acquired.
+ // Write locks may not be acquired if only read locks have been
+ // acquired.
_spinLock.Exit();
throw new LockRecursionException(SR.LockRecursionException_WriteAfterReadNotAllowed);
}
break;
}
- //Check if there is just one upgrader, and no readers.
- //Assumption: Only one thread can have the upgrade lock, so the
- //following check will fail for all other threads that may sneak in
- //when the upgrading thread is waiting.
+ // Check if there is just one upgrader, and no readers.
+ // Assumption: Only one thread can have the upgrade lock, so the
+ // following check will fail for all other threads that may sneak in
+ // when the upgrading thread is waiting.
if (upgradingToWrite)
{
if (readercount == 1)
{
- //Good case again, there is just one upgrader, and no readers.
+ // Good case again, there is just one upgrader, and no readers.
SetWriterAcquired(); // indicate we have a writer.
break;
}
if (lrwc.readercount > 0)
{
- //This check is needed for EU->ER->EW case, as the owner count will be two.
+ // This check is needed for EU->ER->EW case, as the owner count will be two.
Debug.Assert(_fIsReentrant);
Debug.Assert(_fUpgradeThreadHoldingRead);
- //Good case again, there is just one upgrader, and no readers.
+ // Good case again, there is just one upgrader, and no readers.
SetWriterAcquired(); // indicate we have a writer.
break;
}
retVal = WaitOnEvent(_waitUpgradeEvent, ref _numWriteUpgradeWaiters, timeout, EnterLockType.UpgradeToWrite);
- //The lock is not held in case of failure.
+ // The lock is not held in case of failure.
if (!retVal)
return false;
}
}
retVal = WaitOnEvent(_writeEvent, ref _numWriteWaiters, timeout, EnterLockType.Write);
- //The lock is not held in case of failure.
+ // The lock is not held in case of failure.
if (!retVal)
return false;
}
{
if (id == _upgradeLockOwnerId)
{
- //Check for AU->AU
+ // Check for AU->AU
throw new LockRecursionException(SR.LockRecursionException_RecursiveUpgradeNotAllowed);
}
else if (id == _writeLockOwnerId)
{
- //Check for AU->AW
+ // Check for AU->AW
throw new LockRecursionException(SR.LockRecursionException_UpgradeAfterWriteNotAllowed);
}
_spinLock.Enter(EnterSpinLockReason.EnterAnyRead);
lrwc = GetThreadRWCount(dontAllocate: true);
- //Can't acquire upgrade lock with reader lock held.
+ // Can't acquire upgrade lock with reader lock held.
if (lrwc != null && lrwc.readercount > 0)
{
_spinLock.Exit();
}
else if (id == _writeLockOwnerId)
{
- //Write lock is already held, Just update the global state
- //to show presence of upgrader.
+ // Write lock is already held, Just update the global state
+ // to show presence of upgrader.
Debug.Assert((_owners & WRITER_HELD) > 0);
_owners++;
_upgradeLockOwnerId = id;
}
else if (lrwc.readercount > 0)
{
- //Upgrade locks may not be acquired if only read locks have been
- //acquired.
+ // Upgrade locks may not be acquired if only read locks have been
+ // acquired.
_spinLock.Exit();
throw new LockRecursionException(SR.LockRecursionException_UpgradeAfterReadNotAllowed);
}
while (true)
{
- //Once an upgrade lock is taken, it's like having a reader lock held
- //until upgrade or downgrade operations are performed.
+ // Once an upgrade lock is taken, it's like having a reader lock held
+ // until upgrade or downgrade operations are performed.
if ((_upgradeLockOwnerId == -1) && (_owners < MAX_READER))
{
continue; // since we left the lock, start over.
}
- //Only one thread with the upgrade lock held can proceed.
+ // Only one thread with the upgrade lock held can proceed.
retVal = WaitOnEvent(_upgradeEvent, ref _numUpgradeWaiters, timeout, EnterLockType.UpgradeableRead);
if (!retVal)
return false;
if (_fIsReentrant)
{
- //The lock may have been dropped getting here, so make a quick check to see whether some other
- //thread did not grab the entry.
+ // The lock may have been dropped getting here, so make a quick check to see whether some other
+ // thread did not grab the entry.
Debug.Assert(lrwc != null, "Initialized based on _fIsReentrant earlier in the method");
if (IsRwHashEntryChanged(lrwc))
lrwc = GetThreadRWCount(dontAllocate: false)!;
if (lrwc == null || lrwc.readercount < 1)
{
- //You have to be holding the read lock to make this call.
+ // You have to be holding the read lock to make this call.
_spinLock.Exit();
throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedRead);
}
{
if (Environment.CurrentManagedThreadId != _writeLockOwnerId)
{
- //You have to be holding the write lock to make this call.
+ // You have to be holding the write lock to make this call.
throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedWrite);
}
_spinLock.Enter(EnterSpinLockReason.ExitAnyWrite);
{
if (Environment.CurrentManagedThreadId != _upgradeLockOwnerId)
{
- //You have to be holding the upgrade lock to make this call.
+ // You have to be holding the upgrade lock to make this call.
throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedUpgrade);
}
_spinLock.Enter(EnterSpinLockReason.ExitAnyRead);
numWaiters++;
HasNoWaiters = false;
- //Setting these bits will prevent new readers from getting in.
+ // Setting these bits will prevent new readers from getting in.
if (_numWriteWaiters == 1)
SetWritersWaiting();
if (_numWriteUpgradeWaiters == 1)
{
uint readercount = GetNumReaders();
- //We need this case for EU->ER->EW case, as the read count will be 2 in
- //that scenario.
+ // We need this case for EU->ER->EW case, as the read count will be 2 in
+ // that scenario.
if (_fIsReentrant)
{
if (_numWriteUpgradeWaiters > 0 && _fUpgradeThreadHoldingRead && readercount == 2)
if (readercount == 1 && _numWriteUpgradeWaiters > 0)
{
- //We have to be careful now, as we are dropping the lock.
- //No new writes should be allowed to sneak in if an upgrade
- //was pending.
+ // We have to be careful now, as we are dropping the lock.
+ // No new writes should be allowed to sneak in if an upgrade
+ // was pending.
_spinLock.Exit(); // Exit before signaling to improve efficiency (wakee will need the lock)
_waitUpgradeEvent!.Set(); // release all upgraders (however there can be at most one). Known non-null because _numWriteUpgradeWaiters > 0.
_readEvent!.Set(); // release all readers. Known non-null because _numUpgradeWaiters != 0.
if (setUpgradeEvent)
- _upgradeEvent!.Set(); //release one upgrader.
+ _upgradeEvent!.Set(); // release one upgrader.
}
private bool IsWriterAcquired()
{
const int LockSpinCycles = 20;
- //Exponential back-off
+ // Exponential back-off
if ((spinCount < 5) && (ProcessorCount > 1))
{
Thread.SpinWait(LockSpinCycles * spinCount);
if (m_waitHandle != null)
return m_waitHandle;
- //lock the count to avoid multiple threads initializing the handle if it is null
+ // lock the count to avoid multiple threads initializing the handle if it is null
lock (m_lockObjAndDisposed)
{
if (m_waitHandle == null)
nameof(initialCount), initialCount, SR.SemaphoreSlim_ctor_InitialCountWrong);
}
- //validate input
+ // validate input
if (maxCount <= 0)
{
throw new ArgumentOutOfRangeException(nameof(maxCount), maxCount, SR.SemaphoreSlim_ctor_MaxCountWrong);
Task<bool>? asyncWaitTask = null;
bool lockTaken = false;
- //Register for cancellation outside of the main lock.
- //NOTE: Register/unregister inside the lock can deadlock as different lock acquisition orders could
+ // Register for cancellation outside of the main lock.
+ // NOTE: Register/unregister inside the lock can deadlock as different lock acquisition orders could
// occur for (1)this.m_lockObjAndDisposed and (2)cts.internalLock
CancellationTokenRegistration cancellationTokenRegistration = cancellationToken.UnsafeRegister(s_cancellationTokenCanceledEventHandler, this);
try
{
int remainingWaitMilliseconds = Timeout.Infinite;
- //Wait on the monitor as long as the count is zero
+ // Wait on the monitor as long as the count is zero
while (m_currentCount == 0)
{
// If cancelled, we throw. Trying to wait could lead to deadlock.
SemaphoreSlim semaphore = (SemaphoreSlim)obj;
lock (semaphore.m_lockObjAndDisposed)
{
- Monitor.PulseAll(semaphore.m_lockObjAndDisposed); //wake up all waiters.
+ Monitor.PulseAll(semaphore.m_lockObjAndDisposed); // wake up all waiters.
}
}
// Thr thread tracking disabled mask
private const int LOCK_ID_DISABLE_MASK = unchecked((int)0x80000000); // 1000 0000 0000 0000 0000 0000 0000 0000
- //the lock is held by some thread, but we don't know which
+ // the lock is held by some thread, but we don't know which
private const int LOCK_ANONYMOUS_OWNED = 0x1; // 0000 0000 0000 0000 0000 0000 0000 0001
// Waiters mask if the thread tracking is disabled
int observedOwner = _owner;
if (lockTaken || // invalid parameter
(observedOwner & ID_DISABLED_AND_ANONYMOUS_OWNED) != LOCK_ID_DISABLE_MASK || // thread tracking is enabled or the lock is already acquired
- CompareExchange(ref _owner, observedOwner | LOCK_ANONYMOUS_OWNED, observedOwner, ref lockTaken) != observedOwner) //acquiring the lock failed
+ CompareExchange(ref _owner, observedOwner | LOCK_ANONYMOUS_OWNED, observedOwner, ref lockTaken) != observedOwner) // acquiring the lock failed
ContinueTryEnter(Timeout.Infinite, ref lockTaken); // Then try the slow path if any of the above conditions is met
}
public void TryEnter(int millisecondsTimeout, ref bool lockTaken)
{
int observedOwner = _owner;
- if (millisecondsTimeout < -1 || //invalid parameter
- lockTaken || //invalid parameter
- (observedOwner & ID_DISABLED_AND_ANONYMOUS_OWNED) != LOCK_ID_DISABLE_MASK || //thread tracking is enabled or the lock is already acquired
+ if (millisecondsTimeout < -1 || // invalid parameter
+ lockTaken || // invalid parameter
+ (observedOwner & ID_DISABLED_AND_ANONYMOUS_OWNED) != LOCK_ID_DISABLE_MASK || // thread tracking is enabled or the lock is already acquired
CompareExchange(ref _owner, observedOwner | LOCK_ANONYMOUS_OWNED, observedOwner, ref lockTaken) != observedOwner) // acquiring the lock failed
ContinueTryEnter(millisecondsTimeout, ref lockTaken); // The call the slow pth
}
int observedOwner;
int turn = int.MaxValue;
- //***Step 1, take the lock or update the waiters
+ // ***Step 1, take the lock or update the waiters
// try to acquire the lock directly if possible or update the waiters count
observedOwner = _owner;
// Did not acquire lock as owned and timeout is 0 so fail fast
return;
}
- else //failed to acquire the lock, then try to update the waiters. If the waiters count reached the maximum, just break the loop to avoid overflow
+ else // failed to acquire the lock, then try to update the waiters. If the waiters count reached the maximum, just break the loop to avoid overflow
{
if ((observedOwner & WAITERS_MASK) != MAXIMUM_WAITERS)
{
// lock acquired failed and waiters updated
- //*** Step 2, Spinning and Yielding
+ // *** Step 2, Spinning and Yielding
var spinner = new SpinWait();
if (turn > PlatformHelper.ProcessorCount)
{
/// </exception>
public void Exit()
{
- //This is the fast path for the thread tracking is disabled, otherwise go to the slow path
+ // This is the fast path for the thread tracking is disabled, otherwise go to the slow path
if ((_owner & LOCK_ID_DISABLE_MASK) == 0)
ExitSlowPath(true);
else
}
}
- // Uncomment if/when we want Task.FromException
- //// Construct a pre-faulted Task<TResult>
- //internal Task(Exception exception)
- // : base(exception)
- //{
- //}
-
/// <summary>
/// Initializes a new <see cref="Task{TResult}"/> with the specified function.
/// </summary>
try
{
- //if we don't require synchronization, a faster set result path is taken
+ // if we don't require synchronization, a faster set result path is taken
IAsyncResult asyncResult = beginMethod(iar =>
{
if (!iar.CompletedSynchronously)
try
{
- //if we don't require synchronization, a faster set result path is taken
+ // if we don't require synchronization, a faster set result path is taken
IAsyncResult asyncResult = beginMethod(arg1, iar =>
{
if (!iar.CompletedSynchronously)
try
{
- //if we don't require synchronization, a faster set result path is taken
+ // if we don't require synchronization, a faster set result path is taken
IAsyncResult asyncResult = beginMethod(arg1, arg2, iar =>
{
if (!iar.CompletedSynchronously)
try
{
- //if we don't require synchronization, a faster set result path is taken
+ // if we don't require synchronization, a faster set result path is taken
IAsyncResult asyncResult = beginMethod(arg1, arg2, arg3, iar =>
{
if (!iar.CompletedSynchronously)
// check arguments
TaskFactory.CheckMultiTaskContinuationOptions(continuationOptions);
if (tasks == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.tasks);
- //ArgumentNullException of continuationFunction or continuationAction is checked by the caller
+ // ArgumentNullException of continuationFunction or continuationAction is checked by the caller
Debug.Assert((continuationFunction != null) != (continuationAction != null), "Expected exactly one of endFunction/endAction to be non-null");
if (scheduler == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler);
// check arguments
TaskFactory.CheckMultiTaskContinuationOptions(continuationOptions);
if (tasks == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.tasks);
- //ArgumentNullException of continuationFunction or continuationAction is checked by the caller
+ // ArgumentNullException of continuationFunction or continuationAction is checked by the caller
Debug.Assert((continuationFunction != null) != (continuationAction != null), "Expected exactly one of endFunction/endAction to be non-null");
if (scheduler == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler);
if (continuationFunction != null)
{
return starter.ContinueWith(
- //the following delegate avoids closure capture as much as possible
- //completedTasks.Result == tasksCopy;
- //state == continuationFunction
+ // the following delegate avoids closure capture as much as possible
+ // completedTasks.Result == tasksCopy;
+ // state == continuationFunction
(completedTasks, state) =>
{
completedTasks.NotifyDebuggerOfWaitCompletionIfNecessary();
{
Debug.Assert(continuationAction != null);
return starter.ContinueWith<TResult>(
- //the following delegate avoids closure capture as much as possible
- //completedTasks.Result == tasksCopy;
- //state == continuationAction
+ // the following delegate avoids closure capture as much as possible
+ // completedTasks.Result == tasksCopy;
+ // state == continuationAction
(completedTasks, state) =>
{
completedTasks.NotifyDebuggerOfWaitCompletionIfNecessary();
if (tasks == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.tasks);
if (tasks.Length == 0) ThrowHelper.ThrowArgumentException(ExceptionResource.Task_MultiTaskContinuation_EmptyTaskList, ExceptionArgument.tasks);
- //ArgumentNullException of continuationFunction or continuationAction is checked by the caller
+ // ArgumentNullException of continuationFunction or continuationAction is checked by the caller
Debug.Assert((continuationFunction != null) != (continuationAction != null), "Expected exactly one of endFunction/endAction to be non-null");
if (scheduler == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler);
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) =>
{
Debug.Assert(state is Func<Task, TResult>);
{
Debug.Assert(continuationAction != null);
return starter.ContinueWith<TResult>(
- //the following delegate avoids closure capture as much as possible
- //completedTask.Result is the winning task; state == continuationAction
+ // the following delegate avoids closure capture as much as possible
+ // completedTask.Result is the winning task; state == continuationAction
(completedTask, state) =>
{
Debug.Assert(state is Action<Task>);
TaskFactory.CheckMultiTaskContinuationOptions(continuationOptions);
if (tasks == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.tasks);
if (tasks.Length == 0) ThrowHelper.ThrowArgumentException(ExceptionResource.Task_MultiTaskContinuation_EmptyTaskList, ExceptionArgument.tasks);
- //ArgumentNullException of continuationFunction or continuationAction is checked by the caller
+ // ArgumentNullException of continuationFunction or continuationAction is checked by the caller
Debug.Assert((continuationFunction != null) != (continuationAction != null), "Expected exactly one of endFunction/endAction to be non-null");
if (scheduler == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler);
[ThreadStatic]
internal static Task? t_currentTask; // The currently executing task.
- internal static int s_taskIdCounter; //static counter used to generate unique task IDs
+ internal static int s_taskIdCounter; // static counter used to generate unique task IDs
private volatile int m_taskId; // this task's unique ID. initialized only if it is ever requested
// See TaskCreationOptions for bit values associated with TaskCreationOptions
//
private const int OptionsMask = 0xFFFF; // signifies the Options portion of m_stateFlags bin: 0000 0000 0000 0000 1111 1111 1111 1111
- internal const int TASK_STATE_STARTED = 0x10000; //bin: 0000 0000 0000 0001 0000 0000 0000 0000
- internal const int TASK_STATE_DELEGATE_INVOKED = 0x20000; //bin: 0000 0000 0000 0010 0000 0000 0000 0000
- internal const int TASK_STATE_DISPOSED = 0x40000; //bin: 0000 0000 0000 0100 0000 0000 0000 0000
- internal const int TASK_STATE_EXCEPTIONOBSERVEDBYPARENT = 0x80000; //bin: 0000 0000 0000 1000 0000 0000 0000 0000
- internal const int TASK_STATE_CANCELLATIONACKNOWLEDGED = 0x100000; //bin: 0000 0000 0001 0000 0000 0000 0000 0000
- internal const int TASK_STATE_FAULTED = 0x200000; //bin: 0000 0000 0010 0000 0000 0000 0000 0000
- internal const int TASK_STATE_CANCELED = 0x400000; //bin: 0000 0000 0100 0000 0000 0000 0000 0000
- internal const int TASK_STATE_WAITING_ON_CHILDREN = 0x800000; //bin: 0000 0000 1000 0000 0000 0000 0000 0000
- internal const int TASK_STATE_RAN_TO_COMPLETION = 0x1000000; //bin: 0000 0001 0000 0000 0000 0000 0000 0000
- internal const int TASK_STATE_WAITINGFORACTIVATION = 0x2000000; //bin: 0000 0010 0000 0000 0000 0000 0000 0000
- internal const int TASK_STATE_COMPLETION_RESERVED = 0x4000000; //bin: 0000 0100 0000 0000 0000 0000 0000 0000
- internal const int TASK_STATE_WAIT_COMPLETION_NOTIFICATION = 0x10000000; //bin: 0001 0000 0000 0000 0000 0000 0000 0000
- //This could be moved to InternalTaskOptions enum
- internal const int TASK_STATE_EXECUTIONCONTEXT_IS_NULL = 0x20000000; //bin: 0010 0000 0000 0000 0000 0000 0000 0000
- internal const int TASK_STATE_TASKSCHEDULED_WAS_FIRED = 0x40000000; //bin: 0100 0000 0000 0000 0000 0000 0000 0000
+ internal const int TASK_STATE_STARTED = 0x10000; // bin: 0000 0000 0000 0001 0000 0000 0000 0000
+ internal const int TASK_STATE_DELEGATE_INVOKED = 0x20000; // bin: 0000 0000 0000 0010 0000 0000 0000 0000
+ internal const int TASK_STATE_DISPOSED = 0x40000; // bin: 0000 0000 0000 0100 0000 0000 0000 0000
+ internal const int TASK_STATE_EXCEPTIONOBSERVEDBYPARENT = 0x80000; // bin: 0000 0000 0000 1000 0000 0000 0000 0000
+ internal const int TASK_STATE_CANCELLATIONACKNOWLEDGED = 0x100000; // bin: 0000 0000 0001 0000 0000 0000 0000 0000
+ internal const int TASK_STATE_FAULTED = 0x200000; // bin: 0000 0000 0010 0000 0000 0000 0000 0000
+ internal const int TASK_STATE_CANCELED = 0x400000; // bin: 0000 0000 0100 0000 0000 0000 0000 0000
+ internal const int TASK_STATE_WAITING_ON_CHILDREN = 0x800000; // bin: 0000 0000 1000 0000 0000 0000 0000 0000
+ internal const int TASK_STATE_RAN_TO_COMPLETION = 0x1000000; // bin: 0000 0001 0000 0000 0000 0000 0000 0000
+ internal const int TASK_STATE_WAITINGFORACTIVATION = 0x2000000; // bin: 0000 0010 0000 0000 0000 0000 0000 0000
+ internal const int TASK_STATE_COMPLETION_RESERVED = 0x4000000; // bin: 0000 0100 0000 0000 0000 0000 0000 0000
+ internal const int TASK_STATE_WAIT_COMPLETION_NOTIFICATION = 0x10000000; // bin: 0001 0000 0000 0000 0000 0000 0000 0000
+ // This could be moved to InternalTaskOptions enum
+ internal const int TASK_STATE_EXECUTIONCONTEXT_IS_NULL = 0x20000000; // bin: 0010 0000 0000 0000 0000 0000 0000 0000
+ internal const int TASK_STATE_TASKSCHEDULED_WAS_FIRED = 0x40000000; // bin: 0100 0000 0000 0000 0000 0000 0000 0000
// A mask for all of the final states a task may be in.
// SOS DumpAsync command depends on these values.
// A private flag that would be set (only) by the debugger
// When true the Async Causality logging trace is enabled as well as a dictionary to relate operation ids with Tasks
- internal static bool s_asyncDebuggingEnabled; //false by default
+ internal static bool s_asyncDebuggingEnabled; // false by default
// This dictonary relates the task id, from an operation id located in the Async Causality log to the actual
// task. This is to be used by the debugger ONLY. Task in this dictionary represent current active tasks.
{
s_currentActiveTasks[taskId] = task;
}
- //always return true to keep signature as bool for backwards compatibility
+ // always return true to keep signature as bool for backwards compatibility
return true;
}
{
EnsureContingentPropertiesInitializedUnsafe().m_capturedContext = value;
}
- //else do nothing, this is the default context
+ // else do nothing, this is the default context
}
}
if (AsyncCausalityTracer.LoggingOn && (Options & (TaskCreationOptions)InternalTaskOptions.ContinuationTask) == 0)
{
- //For all other task than TaskContinuations we want to log. TaskContinuations log in their constructor
+ // For all other task than TaskContinuations we want to log. TaskContinuations log in their constructor
Debug.Assert(m_action != null, "Must have a delegate to be in ScheduleAndStart");
AsyncCausalityTracer.TraceOperationCreation(this, "Task: " + m_action.Method.Name);
}
internal void CancellationCleanupLogic()
{
Debug.Assert((m_stateFlags & (TASK_STATE_CANCELED | TASK_STATE_COMPLETION_RESERVED)) != 0, "Task.CancellationCleanupLogic(): Task not canceled or reserved.");
- // I'd like to do this, but there is a small window for a race condition. If someone calls Wait() between InternalCancel() and
+ // We'd like to be able to:
+ // Debug.Assert((m_completionEvent == null) || !m_completionEvent.IsSet, "Task.CancellationCleanupLogic(): Completion event already set.");
+ // However, there is a small window for a race condition. If someone calls Wait() between InternalCancel() and
// here, that will set m_completionEvent, leading to a meaningless/harmless assertion.
- //Debug.Assert((m_completionEvent == null) || !m_completionEvent.IsSet, "Task.CancellationCleanupLogic(): Completion event already set.");
// This may have been set already, but we need to make sure.
Interlocked.Exchange(ref m_stateFlags, m_stateFlags | TASK_STATE_CANCELED);
{
Debug.Assert(observedExceptions.Count > 0, "Expected at least one exception");
- //We don't need to TraceOperationCompleted here because TrySetException will call Finish and we'll log it there
+ // We don't need to TraceOperationCompleted here because TrySetException will call Finish and we'll log it there
TrySetException(observedExceptions);
}
{
Debug.Assert(observedExceptions.Count > 0, "Expected at least one exception");
- //We don't need to TraceOperationCompleted here because TrySetException will call Finish and we'll log it there
+ // We don't need to TraceOperationCompleted here because TrySetException will call Finish and we'll log it there
TrySetException(observedExceptions);
}
internal virtual Delegate[]? GetDelegateContinuationsForDebugger()
{
- //Avoid an infinite loop by making sure the continuation object is not a reference to istelf.
+ // Avoid an infinite loop by making sure the continuation object is not a reference to istelf.
if (m_continuationObject != this)
return GetDelegatesFromContinuationObject(m_continuationObject);
else
return delegates;
}
- //We need this ITaskCompletionAction after the Task because in the case of UnwrapPromise
- //the VS debugger is more interested in the continuation than the internal invoke()
+ // We need this ITaskCompletionAction after the Task because in the case of UnwrapPromise
+ // the VS debugger is more interested in the continuation than the internal invoke()
if (continuationObject is ITaskCompletionAction singleCompletionAction)
{
return new Delegate[] { new Action<Task>(singleCompletionAction.Invoke) };
return null;
}
- //Do not remove: VS debugger calls this API directly using func-eval to populate data in the tasks window
+ // Do not remove: VS debugger calls this API directly using func-eval to populate data in the tasks window
private static Task? GetActiveTaskFromId(int taskId)
{
Task? task = null;
Task continuationTask = m_task;
if (isRightKind)
{
- //If the task was cancel before running (e.g a ContinueWhenAll with a cancelled caancelation token)
- //we will still flow it to ScheduleAndStart() were it will check the status before running
- //We check here to avoid faulty logs that contain a join event to an operation that was already set as completed.
+ // If the task was cancel before running (e.g a ContinueWhenAll with a cancelled caancelation token)
+ // we will still flow it to ScheduleAndStart() were it will check the status before running
+ // We check here to avoid faulty logs that contain a join event to an operation that was already set as completed.
if (!continuationTask.IsCanceled && AsyncCausalityTracer.LoggingOn)
{
// Log now that we are sure that this continuation is being ran
// An AppDomain-wide default manager.
private static readonly TaskScheduler s_defaultTaskScheduler = new ThreadPoolTaskScheduler();
- //static counter used to generate unique TaskScheduler IDs
+ // static counter used to generate unique TaskScheduler IDs
internal static int s_taskSchedulerIdCounter;
// this TaskScheduler's unique ID
}
finally
{
- // Only call NWIP() if task was previously queued
+ // Only call NWIP() if task was previously queued
if (taskWasPreviouslyQueued) NotifyWorkItemProgress();
}
/// to ensure that the ThreadLocal<T> does not become initialized if it was not already.</summary>
internal sealed class SystemThreading_ThreadLocalDebugView<T>
{
- //The ThreadLocal object being viewed.
+ // The ThreadLocal object being viewed.
private readonly ThreadLocal<T> _tlocal;
/// <summary>Constructs a new debugger view object for the provided ThreadLocal object.</summary>
i = 0;
foreach (object item in workitems)
{
- if (i < result.Length) //just in case someone calls us while the queues are in motion
+ if (i < result.Length) // just in case someone calls us while the queues are in motion
result[i] = item;
i++;
}
{
long elapsed = TickCount64 - _currentTimerStartTicks;
if (elapsed >= _currentTimerDuration)
- return true; //the timer's about to fire
+ return true; // the timer's about to fire
uint remainingDuration = _currentTimerDuration - (uint)elapsed;
if (actualDuration >= remainingDuration)
- return true; //the timer will fire earlier than this request
+ return true; // the timer will fire earlier than this request
}
if (SetTimer(actualDuration))
{
get
{
- //Grabbing the cached value is required at the top of this function so that
- //we don't incur a race condition with the ResetTimeZone method below.
+ // Grabbing the cached value is required at the top of this function so that
+ // we don't incur a race condition with the ResetTimeZone method below.
TimeZone? tz = currentTimeZone;
if (tz == null)
{
}
}
- //This method is called by CultureInfo.ClearCachedData in response to control panel
- //change events. It must be synchronized because otherwise there is a race condition
- //with the CurrentTimeZone property above.
+ // This method is called by CultureInfo.ClearCachedData in response to control panel
+ // change events. It must be synchronized because otherwise there is a race condition
+ // with the CurrentTimeZone property above.
internal static void ResetTimeZone()
{
if (currentTimeZone != null)
{
}
- //Creates a new WeakReference that keeps track of target.
+ // Creates a new WeakReference that keeps track of target.
//
public WeakReference(T target, bool trackResurrection)
{