Jelajahi Sumber

[System.Private.CoreLib] Initial build pass (#12450)

* [System.Private.CoreLib] Initial build pass

* Add temporary files not officialy converted to allow to build the library

* Formatting changes

* master rebase

* Fixes build

* Doc tests update

* Bump API snapshot submodule
Marek Safar 7 tahun lalu
induk
melakukan
2c6ec113ff
100 mengubah file dengan 17843 tambahan dan 121 penghapusan
  1. 1 1
      external/api-snapshot
  2. 4 0
      mcs/class/System.Private.CoreLib/AssemblyInfo.cs
  3. 112 0
      mcs/class/System.Private.CoreLib/Internal.Runtime.Augments/RuntimeThread.cs
  4. 2 8
      mcs/class/System.Private.CoreLib/Makefile
  5. 13 0
      mcs/class/System.Private.CoreLib/Microsoft.Win32.SafeHandles/SafeWaitHandle.Unix.cs
  6. 60 0
      mcs/class/System.Private.CoreLib/Microsoft.Win32/UnsafeNativeMethods.cs
  7. 1189 0
      mcs/class/System.Private.CoreLib/Resources/SR.cs
  8. 96 0
      mcs/class/System.Private.CoreLib/Stubs.cs
  9. 19 0
      mcs/class/System.Private.CoreLib/System.Collections.Generic/Comparer.cs
  10. 19 0
      mcs/class/System.Private.CoreLib/System.Collections.Generic/EqualityComparer.cs
  11. 15 0
      mcs/class/System.Private.CoreLib/System.Diagnostics.Contracts/Contract.cs
  12. 40 0
      mcs/class/System.Private.CoreLib/System.Diagnostics.Tracing/EventSource.cs
  13. 15 0
      mcs/class/System.Private.CoreLib/System.Diagnostics/Debugger.cs
  14. 14 0
      mcs/class/System.Private.CoreLib/System.Diagnostics/StackFrame.cs
  15. 20 0
      mcs/class/System.Private.CoreLib/System.Diagnostics/StackTrace.cs
  16. 11 0
      mcs/class/System.Private.CoreLib/System.Globalization/CultureData.cs
  17. 17 0
      mcs/class/System.Private.CoreLib/System.Globalization/CultureInfo.cs
  18. 11 0
      mcs/class/System.Private.CoreLib/System.Globalization/GlobalizationMode.cs
  19. 10 0
      mcs/class/System.Private.CoreLib/System.IO/FileLoadException.cs
  20. 15 0
      mcs/class/System.Private.CoreLib/System.IO/Stream.cs
  21. 264 0
      mcs/class/System.Private.CoreLib/System.Private.CoreLib.csproj
  22. 0 2
      mcs/class/System.Private.CoreLib/System.Private.CoreLib.dll.sources
  23. 558 0
      mcs/class/System.Private.CoreLib/System.Reflection.Emit/Stubs.cs
  24. 8 0
      mcs/class/System.Private.CoreLib/System.Reflection.Metadata/AssemblyExtensions.cs
  25. 35 0
      mcs/class/System.Private.CoreLib/System.Reflection/Assembly.cs
  26. 33 0
      mcs/class/System.Private.CoreLib/System.Reflection/AssemblyName.cs
  27. 44 0
      mcs/class/System.Private.CoreLib/System.Reflection/CustomAttributeExtensions.cs
  28. 8 0
      mcs/class/System.Private.CoreLib/System.Reflection/FieldInfo.cs
  29. 30 0
      mcs/class/System.Private.CoreLib/System.Reflection/MethodBase.cs
  30. 37 0
      mcs/class/System.Private.CoreLib/System.Resources/ResourceManager.cs
  31. 8 0
      mcs/class/System.Private.CoreLib/System.Runtime.CompilerServices/RuntimeFeature.cs
  32. 15 0
      mcs/class/System.Private.CoreLib/System.Runtime.CompilerServices/RuntimeHelpers.cs
  33. 9 0
      mcs/class/System.Private.CoreLib/System.Runtime.InteropServices/ComEventsHelper.cs
  34. 9 0
      mcs/class/System.Private.CoreLib/System.Runtime.InteropServices/CriticalHandle.cs
  35. 15 0
      mcs/class/System.Private.CoreLib/System.Runtime.InteropServices/InteropExtensions.cs
  36. 253 0
      mcs/class/System.Private.CoreLib/System.Runtime.InteropServices/Marshal.cs
  37. 38 0
      mcs/class/System.Private.CoreLib/System.Runtime.Loader/AssemblyLoadContext.cs
  38. 13 0
      mcs/class/System.Private.CoreLib/System.Threading/EventWaitHandle.cs
  39. 10 0
      mcs/class/System.Private.CoreLib/System.Threading/Interlocked.cs
  40. 14 0
      mcs/class/System.Private.CoreLib/System.Threading/Mutex.cs
  41. 30 0
      mcs/class/System.Private.CoreLib/System.Threading/Overlapped.cs
  42. 9 0
      mcs/class/System.Private.CoreLib/System.Threading/PreAllocatedOverlapped.cs
  43. 11 0
      mcs/class/System.Private.CoreLib/System.Threading/Semaphore.cs
  44. 19 0
      mcs/class/System.Private.CoreLib/System.Threading/SynchronizationContext.cs
  45. 21 0
      mcs/class/System.Private.CoreLib/System.Threading/Thread.cs
  46. 15 0
      mcs/class/System.Private.CoreLib/System.Threading/ThreadPool.cs
  47. 18 0
      mcs/class/System.Private.CoreLib/System.Threading/ThreadPoolBoundHandle.cs
  48. 19 0
      mcs/class/System.Private.CoreLib/System/Activator.cs
  49. 10 0
      mcs/class/System.Private.CoreLib/System/AppContext.cs
  50. 9 0
      mcs/class/System.Private.CoreLib/System/Array.cs
  51. 38 0
      mcs/class/System.Private.CoreLib/System/Attribute.cs
  52. 13 0
      mcs/class/System.Private.CoreLib/System/DateTime.cs
  53. 9 0
      mcs/class/System.Private.CoreLib/System/DefaultBinder.cs
  54. 81 0
      mcs/class/System.Private.CoreLib/System/Environment.cs
  55. 22 0
      mcs/class/System.Private.CoreLib/System/Exception.cs
  56. 10 0
      mcs/class/System.Private.CoreLib/System/Math.cs
  57. 10 0
      mcs/class/System.Private.CoreLib/System/MathF.cs
  58. 10 0
      mcs/class/System.Private.CoreLib/System/MissingMemberException.cs
  59. 25 0
      mcs/class/System.Private.CoreLib/System/ModuleHandle.cs
  60. 34 0
      mcs/class/System.Private.CoreLib/System/NotImplemented.cs
  61. 17 0
      mcs/class/System.Private.CoreLib/System/Object.cs
  62. 14 0
      mcs/class/System.Private.CoreLib/System/RuntimeFieldHandle.cs
  63. 19 0
      mcs/class/System.Private.CoreLib/System/RuntimeMethodHandle.cs
  64. 26 0
      mcs/class/System.Private.CoreLib/System/RuntimeTypeHandle.cs
  65. 102 0
      mcs/class/System.Private.CoreLib/System/Type.cs
  66. 43 0
      mcs/class/System.Private.CoreLib/temp/AsyncCausalitySupport.cs
  67. 46 0
      mcs/class/System.Private.CoreLib/temp/AsyncCausalityTracer.cs
  68. 388 0
      mcs/class/System.Private.CoreLib/temp/ContractBCL.cs
  69. 45 0
      mcs/class/System.Private.CoreLib/temp/DebuggerSupport.Dummy.cs
  70. 69 0
      mcs/class/System.Private.CoreLib/temp/DebuggerSupport.Mono.cs
  71. 40 0
      mcs/class/System.Private.CoreLib/temp/EnvironmentAugments.cs
  72. 2106 0
      mcs/class/System.Private.CoreLib/temp/FutureFactory.cs
  73. 29 0
      mcs/class/System.Private.CoreLib/temp/GC.cs
  74. 219 0
      mcs/class/System.Private.CoreLib/temp/GCHandleCookieTable.cs
  75. 597 0
      mcs/class/System.Private.CoreLib/temp/TPLETWProvider.cs
  76. 6555 0
      mcs/class/System.Private.CoreLib/temp/Task.cs
  77. 781 0
      mcs/class/System.Private.CoreLib/temp/TaskContinuation.cs
  78. 3043 0
      mcs/class/System.Private.CoreLib/temp/TaskFactory.cs
  79. 71 0
      mcs/class/System.Private.CoreLib/temp/TaskTrace.cs
  80. 10 9
      mcs/class/corlib/ReferenceSources/Buffer.cs
  81. 0 1
      mcs/class/corlib/ReferenceSources/JitHelpers.cs
  82. 4 0
      mcs/class/corlib/ReferenceSources/String.cs
  83. 2 0
      mcs/class/corlib/ReferenceSources/Type.cs
  84. 9 9
      mcs/class/corlib/System.Diagnostics.Tracing/EventSource.cs
  85. 4 1
      mcs/class/corlib/System.Diagnostics/StackTrace.cs
  86. 5 5
      mcs/class/corlib/System.Globalization/CultureInfo.cs
  87. 16 11
      mcs/class/corlib/System.Reflection/AssemblyName.cs
  88. 2 2
      mcs/class/corlib/System.Reflection/CustomAttributeData.cs
  89. 0 3
      mcs/class/corlib/System.Reflection/MonoMethod.cs
  90. 2 0
      mcs/class/corlib/System.Runtime.CompilerServices/ConditionalWeakTable.cs
  91. 11 10
      mcs/class/corlib/System.Runtime.CompilerServices/RuntimeHelpers.cs
  92. 2 2
      mcs/class/corlib/System.Runtime.InteropServices/GCHandle.cs
  93. 1 1
      mcs/class/corlib/System.Threading/Interlocked.cs
  94. 2 0
      mcs/class/corlib/System.Threading/Monitor.cs
  95. 3 3
      mcs/class/corlib/System.Threading/NativeEventCalls.cs
  96. 26 23
      mcs/class/corlib/System.Threading/Thread.cs
  97. 2 2
      mcs/class/corlib/System.Threading/WaitHandle.cs
  98. 9 5
      mcs/class/corlib/System/ArgIterator.cs
  99. 23 18
      mcs/class/corlib/System/Array.cs
  100. 3 5
      mcs/class/corlib/System/Delegate.cs

+ 1 - 1
external/api-snapshot

@@ -1 +1 @@
-Subproject commit f6cd6f186002234b5a5e074918b89a0ba9b12144
+Subproject commit ae8d6a580e22b1feaa2b61b40b47cfd961e92c27

+ 4 - 0
mcs/class/System.Private.CoreLib/AssemblyInfo.cs

@@ -1,3 +1,7 @@
 //
 // System.Private.CoreLib Assembly
 //
+
+using System;
+
+[assembly: CLSCompliant (true)]

+ 112 - 0
mcs/class/System.Private.CoreLib/Internal.Runtime.Augments/RuntimeThread.cs

@@ -0,0 +1,112 @@
+using System;
+using System.Threading;
+using System.Runtime.ConstrainedExecution;
+using System.Runtime.CompilerServices;
+
+namespace Internal.Runtime.Augments
+{
+	public partial class RuntimeThread : CriticalFinalizerObject
+	{
+		// Note: Magic number copied from CoreRT's RuntimeThread.cs. See the original source code for an explanation.
+		internal static readonly int OptimalMaxSpinWaitsPerSpinIteration = 64;
+
+		readonly Thread thread;
+
+		RuntimeThread (Thread t)
+		{
+			thread = t;
+		}
+
+		public bool IsBackground {
+			get { throw new NotImplementedException (); }
+			set { }
+		}
+
+		public static RuntimeThread CurrentThread => throw new NotImplementedException ();
+
+		internal static ulong CurrentOSThreadId {
+			get {
+				throw new NotImplementedException ();
+			}
+		}
+
+		public extern bool IsThreadPoolThread
+		{
+			[MethodImpl (MethodImplOptions.InternalCall)]
+			get;
+		}
+
+		public int ManagedThreadId => AsThread ().ManagedThreadId;
+
+		public string Name {
+			get {
+				return AsThread ().Name;
+			}
+			set {
+				AsThread ().Name = value;
+			}
+		}
+
+		public ThreadPriority Priority {
+			get {
+				throw new NotImplementedException ();
+			}
+			set {
+			}
+		}
+
+		public ThreadState ThreadState {
+			get {
+				throw new NotImplementedException ();
+			}
+		}
+
+		public extern bool IsAlive {
+			[MethodImpl(MethodImplOptions.InternalCall)]
+			get;
+		}
+
+		public static bool Yield () => Thread.Yield ();
+
+		public void Interrupt ()
+		{
+			throw new NotImplementedException ();
+		}
+
+		private Thread AsThread ()
+		{
+			throw new NotImplementedException ();
+		}
+
+		public static RuntimeThread Create (ThreadStart start) => throw new NotImplementedException ();
+		public static RuntimeThread Create (ThreadStart start, int maxStackSize) => throw new NotImplementedException ();
+		public static RuntimeThread Create (ParameterizedThreadStart start) => throw new NotImplementedException ();
+		public static RuntimeThread Create (ParameterizedThreadStart start, int maxStackSize) => throw new NotImplementedException ();
+
+		public static int GetCurrentProcessorId ()
+		{
+			// TODO: Implement correctly
+			return 1;
+		}
+
+		public static bool SpinWait (int iterations)
+		{
+			Thread.SpinWait (iterations);
+			return true;
+		}
+
+		public static void Sleep (int millisecondsTimeout) => Thread.Sleep (millisecondsTimeout);
+
+		public void Start () => throw new NotImplementedException ();
+		public void Start (object parameter) => throw new NotImplementedException ();
+
+		public void Join () => JoinInternal (Timeout.Infinite);
+
+		public bool Join (int millisecondsTimeout) => JoinInternal (millisecondsTimeout);
+
+		private bool JoinInternal (int millisecondsTimeout)
+		{
+			throw new NotImplementedException ();
+		}
+	}
+}

+ 2 - 8
mcs/class/System.Private.CoreLib/Makefile

@@ -2,11 +2,5 @@ thisdir = class/System.Private.CoreLib
 SUBDIRS =
 include ../../build/rules.make
 
-LIBRARY = System.Private.CoreLib.dll
-LIB_REFS =
-EXTRA_DIST_FILES =
-
-LIB_MCS_FLAGS =
-DEFAULT_REFERENCES = 
-
-include ../../build/library.make
+all-local:
+	dotnet build -p:TargetsUnix=true -p:TargetsOSX=true System.Private.CoreLib.csproj

+ 13 - 0
mcs/class/System.Private.CoreLib/Microsoft.Win32.SafeHandles/SafeWaitHandle.Unix.cs

@@ -0,0 +1,13 @@
+using System.Threading;
+
+namespace Microsoft.Win32.SafeHandles
+{
+	partial class SafeWaitHandle
+	{
+		protected override bool ReleaseHandle ()
+		{
+			NativeEventCalls.CloseEvent_internal (handle);
+			return true;
+		}
+	}
+}

+ 60 - 0
mcs/class/System.Private.CoreLib/Microsoft.Win32/UnsafeNativeMethods.cs

@@ -0,0 +1,60 @@
+using System;
+using System.Runtime.InteropServices;
+
+namespace Microsoft.Win32
+{
+	static class UnsafeNativeMethods
+	{
+		internal static unsafe class ManifestEtw
+		{
+			internal unsafe delegate void EtwEnableCallback(
+				[In] ref Guid sourceId,
+				[In] int isEnabled,
+				[In] byte level,
+				[In] long matchAnyKeywords,
+				[In] long matchAllKeywords,
+				[In] EVENT_FILTER_DESCRIPTOR* filterData,
+				[In] void* callbackContext
+				);
+
+			[StructLayout(LayoutKind.Sequential)]
+			unsafe internal struct EVENT_FILTER_DESCRIPTOR
+			{
+				public long Ptr;
+				public int Size;
+				public int Type;
+			}
+
+			internal enum ActivityControl : uint
+			{
+				EVENT_ACTIVITY_CTRL_GET_ID = 1,
+				EVENT_ACTIVITY_CTRL_SET_ID = 2,
+				EVENT_ACTIVITY_CTRL_CREATE_ID = 3,
+				EVENT_ACTIVITY_CTRL_GET_SET_ID = 4,
+				EVENT_ACTIVITY_CTRL_CREATE_SET_ID = 5
+			}
+
+			internal const int ERROR_ARITHMETIC_OVERFLOW = 534;
+			internal const int ERROR_NOT_ENOUGH_MEMORY = 8;
+			internal const int ERROR_MORE_DATA = 0xEA;
+
+			internal const int EVENT_CONTROL_CODE_DISABLE_PROVIDER = 0;
+			internal const int EVENT_CONTROL_CODE_ENABLE_PROVIDER = 1;
+			internal const int EVENT_CONTROL_CODE_CAPTURE_STATE = 2;
+		}
+	}
+
+	// TODO: Should already exist somewhere else
+	static class Win32Native
+	{
+		internal static int GetCurrentThreadId ()
+		{
+			throw new NotImplementedException ();
+		}
+
+		internal static uint GetCurrentProcessId ()
+		{
+			throw new NotImplementedException ();
+		}
+	}
+}

+ 1189 - 0
mcs/class/System.Private.CoreLib/Resources/SR.cs

@@ -0,0 +1,1189 @@
+//
+// This file was generated by resx2sr tool
+//
+
+partial class SR
+{
+	public const string Acc_CreateAbst = "Cannot create an abstract class.";
+	public const string Acc_CreateAbstEx = "Cannot create an instance of {0} because it is an abstract class.";
+	public const string Acc_CreateArgIterator = "Cannot dynamically create an instance of ArgIterator.";
+	public const string Acc_CreateGeneric = "Cannot create a type for which Type.ContainsGenericParameters is true.";
+	public const string Acc_CreateGenericEx = "Cannot create an instance of {0} because Type.ContainsGenericParameters is true.";
+	public const string Acc_CreateInterface = "Cannot create an instance of an interface.";
+	public const string Acc_CreateInterfaceEx = "Cannot create an instance of {0} because it is an interface.";
+	public const string Acc_CreateVoid = "Cannot dynamically create an instance of System.Void.";
+	public const string Acc_NotClassInit = "Type initializer was not callable.";
+	public const string Acc_ReadOnly = "Cannot set a constant field.";
+	public const string Access_Void = "Cannot create an instance of void.";
+	public const string AggregateException_ctor_DefaultMessage = "One or more errors occurred.";
+	public const string AggregateException_ctor_InnerExceptionNull = "An element of innerExceptions was null.";
+	public const string AggregateException_DeserializationFailure = "The serialization stream contains no inner exceptions.";
+	public const string AggregateException_InnerException = "(Inner Exception #{0}) "; // {entry.Item3}
+	public const string AppDomain_AppBaseNotSet = "The ApplicationBase must be set before retrieving this property.";
+	public const string Arg_AccessException = "Cannot access member.";
+	public const string Arg_AccessViolationException = "Attempted to read or write protected memory. This is often an indication that other memory is corrupt.";
+	public const string Arg_AmbiguousMatchException = "Ambiguous match found.";
+	public const string Arg_ApplicationException = "Error in the application.";
+	public const string Arg_ArgumentException = "Value does not fall within the expected range.";
+	public const string Arg_ArgumentOutOfRangeException = "Specified argument was out of the range of valid values.";
+	public const string Arg_ArithmeticException = "Overflow or underflow in the arithmetic operation.";
+	public const string Arg_ArrayLengthsDiffer = "Array lengths must be the same.";
+	public const string Arg_ArrayPlusOffTooSmall = "Destination array is not long enough to copy all the items in the collection. Check array index and length.";
+	public const string Arg_ArrayTypeMismatchException = "Attempted to access an element as a type incompatible with the array.";
+	public const string Arg_ArrayZeroError = "Array must not be of length zero.";
+	public const string Arg_BadDecimal = "Read an invalid decimal value from the buffer.";
+	public const string Arg_BadImageFormatException = "Format of the executable (.exe) or library (.dll) is invalid.";
+	public const string Arg_BadLiteralFormat = "Encountered an invalid type for a default value.";
+	public const string Arg_BogusIComparer = "Unable to sort because the IComparer.Compare() method returns inconsistent results. Either a value does not compare equal to itself, or one value repeatedly compared to another value yields different results. IComparer: '{0}'.";
+	public const string Arg_BufferTooSmall = "Not enough space available in the buffer.";
+	public const string Arg_CannotBeNaN = "TimeSpan does not accept floating point Not-a-Number values.";
+	public const string Arg_CannotHaveNegativeValue = "String cannot contain a minus sign if the base is not 10.";
+	public const string Arg_CannotMixComparisonInfrastructure = "The usage of IKeyComparer and IHashCodeProvider/IComparer interfaces cannot be mixed; use one or the other.";
+	public const string Arg_CATypeResolutionFailed = "Failed to resolve type from string \"{0}\" which was embedded in custom attribute blob.";
+	public const string Arg_COMAccess = "Must specify property Set or Get or method call for a COM Object.";
+	public const string Arg_COMException = "Error HRESULT E_FAIL has been returned from a call to a COM component.";
+	public const string Arg_COMPropSetPut = "Only one of the following binding flags can be set: BindingFlags.SetProperty, BindingFlags.PutDispProperty,  BindingFlags.PutRefDispProperty.";
+	public const string Arg_CreatInstAccess = "Cannot specify both CreateInstance and another access type.";
+	public const string Arg_CryptographyException = "Error occurred during a cryptographic operation.";
+	public const string Arg_CustomAttributeFormatException = "Binary format of the specified custom attribute was invalid.";
+	public const string Arg_DataMisalignedException = "A datatype misalignment was detected in a load or store instruction.";
+	public const string Arg_DateTimeRange = "Combination of arguments to the DateTime constructor is out of the legal range.";
+	public const string Arg_DecBitCtor = "Decimal byte array constructor requires an array of length four containing valid decimal bytes.";
+	public const string Arg_DirectoryNotFoundException = "Attempted to access a path that is not on the disk.";
+	public const string Arg_DivideByZero = "Attempted to divide by zero.";
+	public const string Arg_DlgtNullInst = "Delegate to an instance method cannot have null 'this'.";
+	public const string Arg_DlgtTargMeth = "Cannot bind to the target method because its signature is not compatible with that of the delegate type.";
+	public const string Arg_DlgtTypeMis = "Delegates must be of the same type.";
+	public const string Arg_DllNotFoundException = "Dll was not found.";
+	public const string Arg_DriveNotFoundException = "Attempted to access a drive that is not available.";
+	public const string Arg_DuplicateWaitObjectException = "Duplicate objects in argument.";
+	public const string Arg_EHClauseNotClause = "This ExceptionHandlingClause is not a clause.";
+	public const string Arg_EHClauseNotFilter = "This ExceptionHandlingClause is not a filter.";
+	public const string Arg_EmptyArray = "Array may not be empty.";
+	public const string Arg_EmptyOrNullString = "String may not be empty or null.";
+	public const string Arg_EndOfStreamException = "Attempted to read past the end of the stream.";
+	public const string Arg_EntryPointNotFoundException = "Entry point was not found.";
+	public const string Arg_EnumAndObjectMustBeSameType = "Object must be the same type as the enum. The type passed in was '{0}'; the enum type was '{1}'.";
+	public const string Arg_EnumFormatUnderlyingTypeAndObjectMustBeSameType = "Enum underlying type and the object must be same type or object. Type passed in was '{0}'; the enum underlying type was '{1}'.";
+	public const string Arg_EnumIllegalVal = "Illegal enum value: {0}.";
+	public const string Arg_EnumLitValueNotFound = "Literal value was not found.";
+	public const string Arg_EnumUnderlyingTypeAndObjectMustBeSameType = "Enum underlying type and the object must be same type or object must be a String. Type passed in was '{0}'; the enum underlying type was '{1}'.";
+	public const string Arg_EnumValueNotFound = "Requested value '{0}' was not found.";
+	public const string Arg_ExecutionEngineException = "Internal error in the runtime.";
+	public const string Arg_ExternalException = "External component has thrown an exception.";
+	public const string Arg_FieldAccessException = "Attempted to access a field that is not accessible by the caller.";
+	public const string Arg_FieldDeclTarget = "Field '{0}' defined on type '{1}' is not a field on the target object which is of type '{2}'.";
+	public const string Arg_FldGetArgErr = "No arguments can be provided to Get a field value.";
+	public const string Arg_FldGetPropSet = "Cannot specify both GetField and SetProperty.";
+	public const string Arg_FldSetArgErr = "Only the field value can be specified to set a field value.";
+	public const string Arg_FldSetGet = "Cannot specify both Get and Set on a field.";
+	public const string Arg_FldSetInvoke = "Cannot specify Set on a Field and Invoke on a method.";
+	public const string Arg_FldSetPropGet = "Cannot specify both SetField and GetProperty.";
+	public const string Arg_FormatException = "One of the identified items was in an invalid format.";
+	public const string Arg_GenericParameter = "Method must be called on a Type for which Type.IsGenericParameter is false.";
+	public const string Arg_GetMethNotFnd = "Property Get method was not found.";
+	public const string Arg_GuidArrayCtor = "Byte array for GUID must be exactly {0} bytes long.";
+	public const string Arg_HandleNotAsync = "Handle does not support asynchronous operations. The parameters to the FileStream constructor may need to be changed to indicate that the handle was opened synchronously (that is, it was not opened for overlapped I/O).";
+	public const string Arg_HandleNotSync = "Handle does not support synchronous operations. The parameters to the FileStream constructor may need to be changed to indicate that the handle was opened asynchronously (that is, it was opened explicitly for overlapped I/O).";
+	public const string Arg_HexStyleNotSupported = "The number style AllowHexSpecifier is not supported on floating point data types.";
+	public const string Arg_HTCapacityOverflow = "Hashtable's capacity overflowed and went negative. Check load factor, capacity and the current size of the table.";
+	public const string Arg_IndexMustBeInt = "All indexes must be of type Int32.";
+	public const string Arg_IndexOutOfRangeException = "Index was outside the bounds of the array.";
+	public const string Arg_InsufficientExecutionStackException = "Insufficient stack to continue executing the program safely. This can happen from having too many functions on the call stack or function on the stack using too much stack space.";
+	public const string Arg_InvalidANSIString = "The ANSI string passed in could not be converted from the default ANSI code page to Unicode.";
+	public const string Arg_InvalidBase = "Invalid Base.";
+	public const string Arg_InvalidCastException = "Specified cast is not valid.";
+	public const string Arg_InvalidComObjectException = "Attempt has been made to use a COM object that does not have a backing class factory.";
+	public const string Arg_InvalidFilterCriteriaException = "Specified filter criteria was invalid.";
+	public const string Arg_InvalidHandle = "Invalid handle.";
+	public const string Arg_InvalidHexStyle = "With the AllowHexSpecifier bit set in the enum bit field, the only other valid bits that can be combined into the enum value must be a subset of those in HexNumber.";
+	public const string Arg_InvalidNeutralResourcesLanguage_Asm_Culture = "The NeutralResourcesLanguageAttribute on the assembly \"{0}\" specifies an invalid culture name: \"{1}\".";
+	public const string Arg_InvalidNeutralResourcesLanguage_FallbackLoc = "The NeutralResourcesLanguageAttribute specifies an invalid or unrecognized ultimate resource fallback location: \"{0}\".";
+	public const string Arg_InvalidOleVariantTypeException = "Specified OLE variant was invalid.";
+	public const string Arg_InvalidOperationException = "Operation is not valid due to the current state of the object.";
+	public const string Arg_InvalidSearchPattern = "Search pattern '{0}' cannot contain \"..\" to move up directories and can be contained only internally in file/directory names, as in \"a..b\".";
+	public const string Arg_InvalidTypeInRetType = "The return Type must be a type provided by the runtime.";
+	public const string Arg_InvalidTypeInSignature = "The signature Type array contains some invalid type (i.e. null, void)";
+	public const string Arg_InvalidUTF8String = "The UTF8 string passed in could not be converted to Unicode.";
+	public const string Arg_IOException = "I/O error occurred.";
+	public const string Arg_KeyNotFound = "The given key was not present in the dictionary.";
+	public const string Arg_KeyNotFoundWithKey = "The given key '{0}' was not present in the dictionary.";
+	public const string Arg_LongerThanDestArray = "Destination array was not long enough. Check the destination index, length, and the array's lower bounds.";
+	public const string Arg_LongerThanSrcArray = "Source array was not long enough. Check the source index, length, and the array's lower bounds.";
+	public const string Arg_LongerThanSrcString = "Source string was not long enough. Check sourceIndex and count.";
+	public const string Arg_LowerBoundsMustMatch = "The arrays' lower bounds must be identical.";
+	public const string Arg_MarshalAsAnyRestriction = "AsAny cannot be used on return types, ByRef parameters, ArrayWithOffset, or parameters passed from unmanaged to managed.";
+	public const string Arg_MarshalDirectiveException = "Marshaling directives are invalid.";
+	public const string Arg_MethodAccessException = "Attempt to access the method failed.";
+	public const string Arg_MethodAccessException_WithMethodName = "Attempt to access the method \"{0}\" on type \"{1}\" failed.";
+	public const string Arg_MissingFieldException = "Attempted to access a non-existing field.";
+	public const string Arg_MissingManifestResourceException = "Unable to find manifest resource.";
+	public const string Arg_MissingMemberException = "Attempted to access a missing member.";
+	public const string Arg_MissingMethodException = "Attempted to access a missing method.";
+	public const string Arg_MulticastNotSupportedException = "Attempted to add multiple callbacks to a delegate that does not support multicast.";
+	public const string Arg_MustBeBoolean = "Object must be of type Boolean.";
+	public const string Arg_MustBeByte = "Object must be of type Byte.";
+	public const string Arg_MustBeChar = "Object must be of type Char.";
+	public const string Arg_MustBeDateTime = "Object must be of type DateTime.";
+	public const string Arg_MustBeDateTimeOffset = "Object must be of type DateTimeOffset.";
+	public const string Arg_MustBeDecimal = "Object must be of type Decimal.";
+	public const string Arg_MustBeDelegate = "Type must derive from Delegate.";
+	public const string Arg_MustBeDouble = "Object must be of type Double.";
+	public const string Arg_MustBeEnum = "Type provided must be an Enum.";
+	public const string Arg_MustBeEnumBaseTypeOrEnum = "The value passed in must be an enum base or an underlying type for an enum, such as an Int32.";
+	public const string Arg_MustBeGuid = "Object must be of type GUID.";
+	public const string Arg_MustBeInt16 = "Object must be of type Int16.";
+	public const string Arg_MustBeInt32 = "Object must be of type Int32.";
+	public const string Arg_MustBeInt64 = "Object must be of type Int64.";
+	public const string Arg_MustBeInterface = "Type passed must be an interface.";
+	public const string Arg_MustBePointer = "Type must be a Pointer.";
+	public const string Arg_MustBePrimArray = "Object must be an array of primitives.";
+	public const string Arg_MustBeSByte = "Object must be of type SByte.";
+	public const string Arg_MustBeSingle = "Object must be of type Single.";
+	public const string Arg_MustBeStatic = "Method must be a static method.";
+	public const string Arg_MustBeString = "Object must be of type String.";
+	public const string Arg_MustBeTimeSpan = "Object must be of type TimeSpan.";
+	public const string Arg_MustBeType = "Type must be a type provided by the runtime.";
+	public const string Arg_MustBeUInt16 = "Object must be of type UInt16.";
+	public const string Arg_MustBeUInt32 = "Object must be of type UInt32.";
+	public const string Arg_MustBeUInt64 = "Object must be of type UInt64.";
+	public const string Arg_MustBeVersion = "Object must be of type Version.";
+	public const string Arg_MustContainEnumInfo = "Must specify valid information for parsing in the string.";
+	public const string Arg_NamedParamNull = "Named parameter value must not be null.";
+	public const string Arg_NamedParamTooBig = "Named parameter array cannot be bigger than argument array.";
+	public const string Arg_NDirectBadObject = "No PInvoke conversion exists for value passed to Object-typed parameter.";
+	public const string Arg_Need1DArray = "Array was not a one-dimensional array.";
+	public const string Arg_Need2DArray = "Array was not a two-dimensional array.";
+	public const string Arg_Need3DArray = "Array was not a three-dimensional array.";
+	public const string Arg_NeedAtLeast1Rank = "Must provide at least one rank.";
+	public const string Arg_NegativeArgCount = "Argument count must not be negative.";
+	public const string Arg_NoAccessSpec = "Must specify binding flags describing the invoke operation required (BindingFlags.InvokeMethod CreateInstance GetField SetField GetProperty SetProperty).";
+	public const string Arg_NoDefCTor = "No parameterless constructor defined for type '{0}'.";
+	public const string Arg_NoITypeInfo = "Specified TypeInfo was invalid because it did not support the ITypeInfo interface.";
+	public const string Arg_NoITypeLib = "Specified TypeLib was invalid because it did not support the ITypeLib interface.";
+	public const string Arg_NonZeroLowerBound = "The lower bound of target array must be zero.";
+	public const string Arg_NoStaticVirtual = "Method cannot be both static and virtual.";
+	public const string Arg_NotFiniteNumberException = "Number encountered was not a finite quantity.";
+	public const string Arg_NotFoundIFace = "Interface not found.";
+	public const string Arg_NotGenericMethodDefinition = "{0} is not a GenericMethodDefinition. MakeGenericMethod may only be called on a method for which MethodBase.IsGenericMethodDefinition is true.";
+	public const string Arg_NotGenericParameter = "Method may only be called on a Type for which Type.IsGenericParameter is true.";
+	public const string Arg_NotGenericTypeDefinition = "{0} is not a GenericTypeDefinition. MakeGenericType may only be called on a type for which Type.IsGenericTypeDefinition is true.";
+	public const string Arg_NotImplementedException = "The method or operation is not implemented.";
+	public const string Arg_NotSupportedException = "Specified method is not supported.";
+	public const string Arg_NullIndex = "Arrays indexes must be set to an object instance.";
+	public const string Arg_NullReferenceException = "Object reference not set to an instance of an object.";
+	public const string Arg_ObjObj = "Object type cannot be converted to target type.";
+	public const string Arg_ObjObjEx = "Object of type '{0}' cannot be converted to type '{1}'.";
+	public const string Arg_OleAutDateInvalid = "Not a legal OleAut date.";
+	public const string Arg_OleAutDateScale = "OleAut date did not convert to a DateTime correctly.";
+	public const string Arg_OverflowException = "Arithmetic operation resulted in an overflow.";
+	public const string Arg_OutOfMemoryException = "Insufficient memory to continue the execution of the program.";
+	public const string Arg_ParamName_Name = "Parameter name: {0}";
+	public const string Arg_ParmArraySize = "Must specify one or more parameters.";
+	public const string Arg_ParmCnt = "Parameter count mismatch.";
+	public const string Arg_PathEmpty = "The path is empty.";
+	public const string Arg_PathIllegalUNC_Path = "The UNC path '{0}' should be of the form \\\\\\\\server\\\\share.";
+	public const string Arg_PlatformNotSupported = "Operation is not supported on this platform.";
+	public const string Arg_PrimWiden = "Cannot widen from source type to target type either because the source type is a not a primitive type or the conversion cannot be accomplished.";
+	public const string Arg_PropSetGet = "Cannot specify both Get and Set on a property.";
+	public const string Arg_PropSetInvoke = "Cannot specify Set on a property and Invoke on a method.";
+	public const string Arg_RankException = "Attempted to operate on an array with the incorrect number of dimensions.";
+	public const string Arg_RankIndices = "Indices length does not match the array rank.";
+	public const string Arg_RankMultiDimNotSupported = "Only single dimensional arrays are supported for the requested action.";
+	public const string Arg_RanksAndBounds = "Number of lengths and lowerBounds must match.";
+	public const string Arg_RegGetOverflowBug = "RegistryKey.GetValue does not allow a String that has a length greater than Int32.MaxValue.";
+	public const string Arg_RegKeyNotFound = "The specified registry key does not exist.";
+	public const string Arg_RegSubKeyValueAbsent = "No value exists with that name.";
+	public const string Arg_RegValStrLenBug = "Registry value names should not be greater than 16,383 characters.";
+	public const string Arg_ResMgrNotResSet = "Type parameter must refer to a subclass of ResourceSet.";
+	public const string Arg_ResourceFileUnsupportedVersion = "The ResourceReader class does not know how to read this version of .resources files. Expected version: {0}  This file: {1}";
+	public const string Arg_ResourceNameNotExist = "The specified resource name \"{0}\" does not exist in the resource file.";
+	public const string Arg_SafeArrayRankMismatchException = "Specified array was not of the expected rank.";
+	public const string Arg_SafeArrayTypeMismatchException = "Specified array was not of the expected type.";
+	public const string Arg_SecurityException = "Security error.";
+	public const string SerializationException = "Serialization error.";
+	public const string Arg_SetMethNotFnd = "Property set method not found.";
+	public const string Arg_StackOverflowException = "Operation caused a stack overflow.";
+	public const string Arg_SurrogatesNotAllowedAsSingleChar = "Unicode surrogate characters must be written out as pairs together in the same call, not individually. Consider passing in a character array instead.";
+	public const string Arg_SynchronizationLockException = "Object synchronization method was called from an unsynchronized block of code.";
+	public const string Arg_SystemException = "System error.";
+	public const string Arg_TargetInvocationException = "Exception has been thrown by the target of an invocation.";
+	public const string Arg_TargetParameterCountException = "Number of parameters specified does not match the expected number.";
+	public const string Arg_ThreadStartException = "Thread failed to start.";
+	public const string Arg_ThreadStateException = "Thread was in an invalid state for the operation being executed.";
+	public const string Arg_TimeoutException = "The operation has timed out.";
+	public const string Arg_TypeAccessException = "Attempt to access the type failed.";
+	public const string Arg_TypedReference_Null = "The TypedReference must be initialized.";
+	public const string Arg_TypeLoadException = "Failure has occurred while loading a type.";
+	public const string Arg_TypeLoadNullStr = "A null or zero length string does not represent a valid Type.";
+	public const string Arg_TypeRefPrimitve = "TypedReferences cannot be redefined as primitives. Field name '{0}'.";
+	public const string Arg_TypeUnloadedException = "Type had been unloaded.";
+	public const string Arg_UnauthorizedAccessException = "Attempted to perform an unauthorized operation.";
+	public const string Arg_UnboundGenField = "Late bound operations cannot be performed on fields with types for which Type.ContainsGenericParameters is true.";
+	public const string Arg_UnboundGenParam = "Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true.";
+	public const string Arg_UnknownTypeCode = "Unknown TypeCode value.";
+	public const string Arg_VarMissNull = "Missing parameter does not have a default value.";
+	public const string Arg_VersionString = "Version string portion was too short or too long.";
+	public const string Arg_WrongAsyncResult = "IAsyncResult object did not come from the corresponding async method on this type.";
+	public const string Arg_WrongType = "The value \"{0}\" is not of type \"{1}\" and cannot be used in this generic collection.";
+	public const string Argument_AbsolutePathRequired = "Absolute path information is required.";
+	public const string Argument_AddingDuplicate = "An item with the same key has already been added.";
+	public const string Argument_AddingDuplicate__ = "Item has already been added. Key in dictionary: '{0}'  Key being added: '{1}'";
+	public const string Argument_AddingDuplicateWithKey = "An item with the same key has already been added. Key: {0}";
+	public const string Argument_AdjustmentRulesNoNulls = "The AdjustmentRule array cannot contain null elements.";
+	public const string Argument_AdjustmentRulesOutOfOrder = "The elements of the AdjustmentRule array must be in chronological order and must not overlap.";
+	public const string Argument_AlreadyACCW = "The object already has a CCW associated with it.";
+	public const string Argument_AlreadyBoundOrSyncHandle = "'handle' has already been bound to the thread pool, or was not opened for asynchronous I/O.";
+	public const string Argument_ArgumentZero = "Argument cannot be zero.";
+	public const string Argument_ArrayGetInterfaceMap = "Interface maps for generic interfaces on arrays cannot be retrieved.";
+	public const string Argument_ArraysInvalid = "Array or pointer types are not valid.";
+	public const string Argument_BadAttributeOnInterfaceMethod = "Interface method must be abstract and virtual.";
+	public const string Argument_BadConstantValue = "Bad default value.";
+	public const string Argument_BadConstructor = "Cannot have private or static constructor.";
+	public const string Argument_BadConstructorCallConv = "Constructor must have standard calling convention.";
+	public const string Argument_BadExceptionCodeGen = "Incorrect code generation for exception block.";
+	public const string Argument_BadFieldForConstructorBuilder = "Field must be on the same type of the given ConstructorInfo.";
+	public const string Argument_BadFieldSig = "Field signatures do not have return types.";
+	public const string Argument_BadFieldType = "Bad field type in defining field.";
+	public const string Argument_BadFormatSpecifier = "Format specifier was invalid.";
+	public const string Argument_BadImageFormatExceptionResolve = "A BadImageFormatException has been thrown while parsing the signature. This is likely due to lack of a generic context. Ensure genericTypeArguments and genericMethodArguments are provided and contain enough context.";
+	public const string Argument_BadLabel = "Bad label in ILGenerator.";
+	public const string Argument_BadLabelContent = "Bad label content in ILGenerator.";
+	public const string Argument_BadNestedTypeFlags = "Visibility of interfaces must be one of the following: NestedAssembly, NestedFamANDAssem, NestedFamily, NestedFamORAssem, NestedPrivate or NestedPublic.";
+	public const string Argument_BadObjRef = "Invalid ObjRef provided to '{0}'.";
+	public const string Argument_BadParameterCountsForConstructor = "Parameter count does not match passed in argument value count.";
+	public const string Argument_BadParameterTypeForCAB = "Cannot emit a CustomAttribute with argument of type {0}.";
+	public const string Argument_BadPropertyForConstructorBuilder = "Property must be on the same type of the given ConstructorInfo.";
+	public const string Argument_BadSigFormat = "Incorrect signature format.";
+	public const string Argument_BadSizeForData = "Data size must be > 1 and < 0x3f0000";
+	public const string Argument_BadTypeAttrInvalidLayout = "Bad type attributes. Invalid layout attribute specified.";
+	public const string Argument_BadTypeAttrNestedVisibilityOnNonNestedType = "Bad type attributes. Nested visibility flag set on a non-nested type.";
+	public const string Argument_BadTypeAttrNonNestedVisibilityNestedType = "Bad type attributes. Non-nested visibility flag set on a nested type.";
+	public const string Argument_BadTypeAttrReservedBitsSet = "Bad type attributes. Reserved bits set on the type.";
+	public const string Argument_BadTypeInCustomAttribute = "An invalid type was used as a custom attribute constructor argument, field or property.";
+	public const string Argument_CannotCreateTypedReference = "Cannot use function evaluation to create a TypedReference object.";
+	public const string Argument_CannotGetTypeTokenForByRef = "Cannot get TypeToken for a ByRef type.";
+	public const string Argument_CannotSetParentToInterface = "Cannot set parent to an interface.";
+	public const string Argument_CodepageNotSupported = "{0} is not a supported code page.";
+	public const string Argument_CompareOptionOrdinal = "CompareOption.Ordinal cannot be used with other options.";
+	public const string Argument_ConflictingDateTimeRoundtripStyles = "The DateTimeStyles value RoundtripKind cannot be used with the values AssumeLocal, AssumeUniversal or AdjustToUniversal.";
+	public const string Argument_ConflictingDateTimeStyles = "The DateTimeStyles values AssumeLocal and AssumeUniversal cannot be used together.";
+	public const string Argument_ConstantDoesntMatch = "Constant does not match the defined type.";
+	public const string Argument_ConstantNotSupported = "{0} is not a supported constant type.";
+	public const string Argument_ConstantNull = "Null is not a valid constant value for this type.";
+	public const string Argument_ConstructorNeedGenericDeclaringType = "The specified constructor must be declared on a generic type definition.";
+	public const string Argument_ConversionOverflow = "Conversion buffer overflow.";
+	public const string Argument_ConvertMismatch = "The conversion could not be completed because the supplied DateTime did not have the Kind property set correctly.  For example, when the Kind property is DateTimeKind.Local, the source time zone must be TimeZoneInfo.Local.";
+	public const string Argument_CORDBBadMethod = "Cannot find the method on the object instance.";
+	public const string Argument_CORDBBadVarArgCallConv = "Cannot evaluate a VarArgs function.";
+	public const string Argument_CultureIetfNotSupported = "Culture IETF Name {0} is not a recognized IETF name.";
+	public const string Argument_CultureInvalidIdentifier = "{0} is an invalid culture identifier.";
+	public const string Argument_CultureIsNeutral = "Culture ID {0} (0x{0:X4}) is a neutral culture; a region cannot be created from it.";
+	public const string Argument_CultureNotSupported = "Culture is not supported.";
+	public const string Argument_CustomAssemblyLoadContextRequestedNameMismatch = "Resolved assembly's simple name should be the same as of the requested assembly.";
+	public const string Argument_CustomCultureCannotBePassedByNumber = "Customized cultures cannot be passed by LCID, only by name.";
+	public const string Argument_DateTimeBadBinaryData = "The binary data must result in a DateTime with ticks between DateTime.MinValue.Ticks and DateTime.MaxValue.Ticks.";
+	public const string Argument_DateTimeHasTicks = "The supplied DateTime must have the Year, Month, and Day properties set to 1.  The time cannot be specified more precisely than whole milliseconds.";
+	public const string Argument_DateTimeHasTimeOfDay = "The supplied DateTime includes a TimeOfDay setting.   This is not supported.";
+	public const string Argument_DateTimeIsInvalid = "The supplied DateTime represents an invalid time.  For example, when the clock is adjusted forward, any time in the period that is skipped is invalid.";
+	public const string Argument_DateTimeIsNotAmbiguous = "The supplied DateTime is not in an ambiguous time range.";
+	public const string Argument_DateTimeKindMustBeUnspecified = "The supplied DateTime must have the Kind property set to DateTimeKind.Unspecified.";
+	public const string Argument_DateTimeKindMustBeUnspecifiedOrUtc = "The supplied DateTime must have the Kind property set to DateTimeKind.Unspecified or DateTimeKind.Utc.";
+	public const string Argument_DateTimeOffsetInvalidDateTimeStyles = "The DateTimeStyles value 'NoCurrentDateDefault' is not allowed when parsing DateTimeOffset.";
+	public const string Argument_DateTimeOffsetIsNotAmbiguous = "The supplied DateTimeOffset is not in an ambiguous time range.";
+	public const string Argument_DestinationTooShort = "Destination is too short.";
+	public const string Argument_DuplicateTypeName = "Duplicate type name within an assembly.";
+	public const string Argument_EmitWriteLineType = "EmitWriteLine does not support this field or local type.";
+	public const string Argument_EmptyDecString = "Decimal separator cannot be the empty string.";
+	public const string Argument_EmptyFileName = "Empty file name is not legal.";
+	public const string Argument_EmptyName = "Empty name is not legal.";
+	public const string Argument_EmptyPath = "Empty path name is not legal.";
+	public const string Argument_EmptyWaithandleArray = "Waithandle array may not be empty.";
+	public const string Argument_EncoderFallbackNotEmpty = "Must complete Convert() operation or call Encoder.Reset() before calling GetBytes() or GetByteCount(). Encoder '{0}' fallback '{1}'.";
+	public const string Argument_EncodingConversionOverflowBytes = "The output byte buffer is too small to contain the encoded data, encoding '{0}' fallback '{1}'.";
+	public const string Argument_EncodingConversionOverflowChars = "The output char buffer is too small to contain the decoded characters, encoding '{0}' fallback '{1}'.";
+	public const string Argument_EncodingNotSupported = "'{0}' is not a supported encoding name. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method.";
+	public const string Argument_EnumTypeDoesNotMatch = "The argument type, '{0}', is not the same as the enum type '{1}'.";
+	public const string Argument_FallbackBufferNotEmpty = "Cannot change fallback when buffer is not empty. Previous Convert() call left data in the fallback buffer.";
+	public const string Argument_FieldDeclaringTypeGeneric = "Cannot resolve field {0} because the declaring type of the field handle {1} is generic. Explicitly provide the declaring type to GetFieldFromHandle.";
+	public const string Argument_FieldNeedGenericDeclaringType = "The specified field must be declared on a generic type definition.";
+	public const string Argument_GenConstraintViolation = "GenericArguments[{0}], '{1}', on '{2}' violates the constraint of type '{3}'.";
+	public const string Argument_GenericArgsCount = "The number of generic arguments provided doesn't equal the arity of the generic type definition.";
+	public const string Argument_GenericsInvalid = "Generic types are not valid.";
+	public const string Argument_GlobalFunctionHasToBeStatic = "Global members must be static.";
+	public const string Argument_HandleLeak = "Cannot pass a GCHandle across AppDomains.";
+	public const string Argument_HasToBeArrayClass = "Must be an array type.";
+	public const string Argument_IdnBadBidi = "Left to right characters may not be mixed with right to left characters in IDN labels.";
+	public const string Argument_IdnBadLabelSize = "IDN labels must be between 1 and 63 characters long.";
+	public const string Argument_IdnBadNameSize = "IDN names must be between 1 and {0} characters long.";
+	public const string Argument_IdnBadPunycode = "Invalid IDN encoded string.";
+	public const string Argument_IdnBadStd3 = "Label contains character '{0}' not allowed with UseStd3AsciiRules";
+	public const string Argument_IdnIllegalName = "Decoded string is not a valid IDN name.";
+	public const string Argument_IllegalEnvVarName = "Environment variable name cannot contain equal character.";
+	public const string Argument_IllegalName = "Illegal name.";
+	public const string Argument_ImplementIComparable = "At least one object must implement IComparable.";
+	public const string Argument_IndexOutOfArrayBounds = "The specified index is out of bounds of the specified array.";
+	public const string Argument_InsufficientSpaceToCopyCollection = "The specified space is not sufficient to copy the elements from this Collection.";
+	public const string Argument_InterfaceMap = "'this' type cannot be an interface itself.";
+	public const string Argument_InvalidAppendMode = "Append access can be requested only in write-only mode.";
+	public const string Argument_InvalidArgumentForComparison = "Type of argument is not compatible with the generic comparer.";
+	public const string Argument_InvalidArrayLength = "Length of the array must be {0}.";
+	public const string Argument_InvalidArrayType = "Target array type is not compatible with the type of items in the collection.";
+	public const string Argument_InvalidAssemblyName = "Assembly names may not begin with whitespace or contain the characters '/', or '\\\\' or ':'.";
+	public const string Argument_InvalidCalendar = "Not a valid calendar for the given culture.";
+	public const string Argument_InvalidCharSequence = "Invalid Unicode code point found at index {0}.";
+	public const string Argument_InvalidCharSequenceNoIndex = "String contains invalid Unicode code points.";
+	public const string Argument_InvalidCodePageBytesIndex = "Unable to translate bytes {0} at index {1} from specified code page to Unicode.";
+	public const string Argument_InvalidCodePageConversionIndex = "Unable to translate Unicode character \\\\u{0:X4} at index {1} to specified code page.";
+	public const string Argument_InvalidConstructorDeclaringType = "The specified constructor must be declared on the generic type definition of the specified type.";
+	public const string Argument_InvalidConstructorInfo = "The ConstructorInfo object is not valid.";
+	public const string Argument_InvalidCultureName = "Culture name '{0}' is not supported.";
+	public const string Argument_InvalidDateTimeKind = "Invalid DateTimeKind value.";
+	public const string Argument_InvalidDateTimeStyles = "An undefined DateTimeStyles value is being used.";
+	public const string Argument_InvalidDigitSubstitution = "The DigitSubstitution property must be of a valid member of the DigitShapes enumeration. Valid entries include Context, NativeNational or None.";
+	public const string Argument_InvalidEnum = "The Enum type should contain one and only one instance field.";
+	public const string Argument_InvalidEnumValue = "The value '{0}' is not valid for this usage of the type {1}.";
+	public const string Argument_InvalidFieldDeclaringType = "The specified field must be declared on the generic type definition of the specified type.";
+	public const string Argument_InvalidFileModeAndAccessCombo = "Combining FileMode: {0} with FileAccess: {1} is invalid.";
+	public const string Argument_InvalidFlag = "Value of flags is invalid.";
+	public const string Argument_InvalidGenericArg = "The generic type parameter was not valid";
+	public const string Argument_InvalidGenericInstArray = "Generic arguments must be provided for each generic parameter and each generic argument must be a RuntimeType.";
+	public const string Argument_InvalidGroupSize = "Every element in the value array should be between one and nine, except for the last element, which can be zero.";
+	public const string Argument_InvalidHandle = "The handle is invalid.";
+	public const string Argument_InvalidHighSurrogate = "Found a high surrogate char without a following low surrogate at index: {0}. The input may not be in this encoding, or may not contain valid Unicode (UTF-16) characters.";
+	public const string Argument_InvalidId = "The specified ID parameter '{0}' is not supported.";
+	public const string Argument_InvalidKindOfTypeForCA = "This type cannot be represented as a custom attribute.";
+	public const string Argument_InvalidLabel = "Invalid Label.";
+	public const string Argument_InvalidLowSurrogate = "Found a low surrogate char without a preceding high surrogate at index: {0}. The input may not be in this encoding, or may not contain valid Unicode (UTF-16) characters.";
+	public const string Argument_InvalidMemberForNamedArgument = "The member must be either a field or a property.";
+	public const string Argument_InvalidMethodDeclaringType = "The specified method must be declared on the generic type definition of the specified type.";
+	public const string Argument_InvalidName = "Invalid name.";
+	public const string Argument_InvalidNativeDigitCount = "The NativeDigits array must contain exactly ten members.";
+	public const string Argument_InvalidNativeDigitValue = "Each member of the NativeDigits array must be a single text element (one or more UTF16 code points) with a Unicode Nd (Number, Decimal Digit) property indicating it is a digit.";
+	public const string Argument_InvalidNeutralRegionName = "The region name {0} should not correspond to neutral culture; a specific culture name is required.";
+	public const string Argument_InvalidNormalizationForm = "Invalid or unsupported normalization form.";
+	public const string Argument_InvalidNumberStyles = "An undefined NumberStyles value is being used.";
+	public const string Argument_InvalidOffLen = "Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection.";
+	public const string Argument_InvalidOpCodeOnDynamicMethod = "Ldtoken, Ldftn and Ldvirtftn OpCodes cannot target DynamicMethods.";
+	public const string Argument_InvalidParameterInfo = "The ParameterInfo object is not valid.";
+	public const string Argument_InvalidParamInfo = "Invalid type for ParameterInfo member in Attribute class.";
+	public const string Argument_InvalidPathChars = "Illegal characters in path.";
+	public const string Argument_InvalidRegistryViewCheck = "The specified RegistryView value is invalid.";
+	public const string Argument_InvalidResourceCultureName = "The given culture name '{0}' cannot be used to locate a resource file. Resource filenames must consist of only letters, numbers, hyphens or underscores.";
+	public const string Argument_InvalidSafeBufferOffLen = "Offset and length were greater than the size of the SafeBuffer.";
+	public const string Argument_InvalidSeekOrigin = "Invalid seek origin.";
+	public const string Argument_InvalidSerializedString = "The specified serialized string '{0}' is not supported.";
+	public const string Argument_InvalidStartupHookSyntax = "The syntax of the startup hook variable was invalid.";
+	public const string Argument_InvalidStartupHookSignature = "The signature of the startup hook '{0}' in assembly '{1}' was invalid. It must be 'public static void Initialize()'.";
+	public const string Argument_InvalidTimeSpanStyles = "An undefined TimeSpanStyles value is being used.";
+	public const string Argument_InvalidToken = "Token {0:x} is not valid in the scope of module {1}.";
+	public const string Argument_InvalidTypeForCA = "Cannot build type parameter for custom attribute with a type that does not support the AssemblyQualifiedName property. The type instance supplied was of type '{0}'.";
+	public const string Argument_InvalidTypeForDynamicMethod = "Invalid type owner for DynamicMethod.";
+	public const string Argument_InvalidTypeName = "The name of the type is invalid.";
+	public const string Argument_InvalidTypeWithPointersNotSupported = "Cannot use type '{0}'. Only value types without pointers or references are supported.";
+	public const string Argument_InvalidUnity = "Type '{0}' is not deserializable.";
+	public const string Argument_InvalidValue = "Value was invalid.";
+	public const string Argument_LargeInteger = "Integer or token was too large to be encoded.";
+	public const string Argument_LongEnvVarValue = "Environment variable name or value is too long.";
+	public const string Argument_MethodDeclaringTypeGeneric = "Cannot resolve method {0} because the declaring type of the method handle {1} is generic. Explicitly provide the declaring type to GetMethodFromHandle.";
+	public const string Argument_MethodDeclaringTypeGenericLcg = "Method '{0}' has a generic declaring type '{1}'. Explicitly provide the declaring type to GetTokenFor.";
+	public const string Argument_MethodNeedGenericDeclaringType = "The specified method cannot be dynamic or global and must be declared on a generic type definition.";
+	public const string Argument_MinMaxValue = "'{0}' cannot be greater than {1}.";
+	public const string Argument_MismatchedArrays = "Two arrays, {0} and {1}, must be of  the same size.";
+	public const string Argument_MissingDefaultConstructor = "was missing default constructor.";
+	public const string Argument_MustBeFalse = "Argument must be initialized to false";
+	public const string Argument_MustBeRuntimeAssembly = "Assembly must be a runtime Assembly object.";
+	public const string Argument_MustBeRuntimeFieldInfo = "FieldInfo must be a runtime FieldInfo object.";
+	public const string Argument_MustBeRuntimeMethodInfo = "MethodInfo must be a runtime MethodInfo object.";
+	public const string Argument_MustBeRuntimeReflectionObject = "The object must be a runtime Reflection object.";
+	public const string Argument_MustBeRuntimeType = "Type must be a runtime Type object.";
+	public const string Argument_MustBeTypeBuilder = "'type' must contain a TypeBuilder as a generic argument.";
+	public const string Argument_MustHaveAttributeBaseClass = "Type passed in must be derived from System.Attribute or System.Attribute itself.";
+	public const string Argument_MustHaveLayoutOrBeBlittable = "The specified structure must be blittable or have layout information.";
+	public const string Argument_NativeOverlappedAlreadyFree = "'overlapped' has already been freed.";
+	public const string Argument_NativeOverlappedWrongBoundHandle = "'overlapped' was not allocated by this ThreadPoolBoundHandle instance.";
+	public const string Argument_NeedGenericMethodDefinition = "Method must represent a generic method definition on a generic type definition.";
+	public const string Argument_NeedNonGenericObject = "The specified object must not be an instance of a generic type.";
+	public const string Argument_NeedNonGenericType = "The specified Type must not be a generic type definition.";
+	public const string Argument_NeedStructWithNoRefs = "The specified Type must be a struct containing no references.";
+	public const string Argument_NeverValidGenericArgument = "The type '{0}' may not be used as a type argument.";
+	public const string Argument_NoDomainManager = "The domain manager specified by the host could not be instantiated.";
+	public const string Argument_NoEra = "No Era was supplied.";
+	public const string Argument_NoModuleFileExtension = "Module file name '{0}' must have file extension.";
+	public const string Argument_NoRegionInvariantCulture = "There is no region associated with the Invariant Culture (Culture ID: 0x7F).";
+	public const string Argument_NotATP = "Type must be a TransparentProxy";
+	public const string Argument_NotAWritableProperty = "Not a writable property.";
+	public const string Argument_NotEnoughBytesToRead = "There are not enough bytes remaining in the accessor to read at this position.";
+	public const string Argument_NotEnoughBytesToWrite = "There are not enough bytes remaining in the accessor to write at this position.";
+	public const string Argument_NotEnoughGenArguments = "The type or method has {1} generic parameter(s), but {0} generic argument(s) were provided. A generic argument must be provided for each generic parameter.";
+	public const string Argument_NotExceptionType = "Does not extend Exception.";
+	public const string Argument_NotInExceptionBlock = "Not currently in an exception block.";
+	public const string Argument_NotMethodCallOpcode = "The specified opcode cannot be passed to EmitCall.";
+	public const string Argument_NotSerializable = "Argument passed in is not serializable.";
+	public const string Argument_NoUnderlyingCCW = "The object has no underlying COM data associated with it.";
+	public const string Argument_NoUninitializedStrings = "Uninitialized Strings cannot be created.";
+	public const string Argument_ObjIsWinRTObject = "The object's type must not be a Windows Runtime type.";
+	public const string Argument_ObjNotComObject = "The object's type must be __ComObject or derived from __ComObject.";
+	public const string Argument_OffsetAndCapacityOutOfBounds = "Offset and capacity were greater than the size of the view.";
+	public const string Argument_OffsetLocalMismatch = "The UTC Offset of the local dateTime parameter does not match the offset argument.";
+	public const string Argument_OffsetOfFieldNotFound = "Field passed in is not a marshaled member of the type '{0}'.";
+	public const string Argument_OffsetOutOfRange = "Offset must be within plus or minus 14 hours.";
+	public const string Argument_OffsetPrecision = "Offset must be specified in whole minutes.";
+	public const string Argument_OffsetUtcMismatch = "The UTC Offset for Utc DateTime instances must be 0.";
+	public const string Argument_OneOfCulturesNotSupported = "Culture name {0} or {1} is not supported.";
+	public const string Argument_OnlyMscorlib = "Only mscorlib's assembly is valid.";
+	public const string Argument_OutOfOrderDateTimes = "The DateStart property must come before the DateEnd property.";
+	public const string Argument_PathEmpty = "Path cannot be the empty string or all whitespace.";
+	public const string Argument_PathFormatNotSupported_Path = "The format of the path '{0}' is not supported.";
+	public const string Argument_PreAllocatedAlreadyAllocated = "'preAllocated' is already in use.";
+	public const string Argument_RecursiveFallback = "Recursive fallback not allowed for character \\\\u{0:X4}.";
+	public const string Argument_RecursiveFallbackBytes = "Recursive fallback not allowed for bytes {0}.";
+	public const string Argument_RedefinedLabel = "Label multiply defined.";
+	public const string Argument_ResolveField = "Token {0:x} is not a valid FieldInfo token in the scope of module {1}.";
+	public const string Argument_ResolveFieldHandle = "Type handle '{0}' and field handle with declaring type '{1}' are incompatible. Get RuntimeFieldHandle and declaring RuntimeTypeHandle off the same FieldInfo.";
+	public const string Argument_ResolveMember = "Token {0:x} is not a valid MemberInfo token in the scope of module {1}.";
+	public const string Argument_ResolveMethod = "Token {0:x} is not a valid MethodBase token in the scope of module {1}.";
+	public const string Argument_ResolveMethodHandle = "Type handle '{0}' and method handle with declaring type '{1}' are incompatible. Get RuntimeMethodHandle and declaring RuntimeTypeHandle off the same MethodBase.";
+	public const string Argument_ResolveModuleType = "Token {0} resolves to the special module type representing this module.";
+	public const string Argument_ResolveString = "Token {0:x} is not a valid string token in the scope of module {1}.";
+	public const string Argument_ResolveType = "Token {0:x} is not a valid Type token in the scope of module {1}.";
+	public const string Argument_ResultCalendarRange = "The result is out of the supported range for this calendar. The result should be between {0} (Gregorian date) and {1} (Gregorian date), inclusive.";
+	public const string Argument_SemaphoreInitialMaximum = "The initial count for the semaphore must be greater than or equal to zero and less than the maximum count.";
+	public const string Argument_ShouldNotSpecifyExceptionType = "Should not specify exception type for catch clause for filter block.";
+	public const string Argument_ShouldOnlySetVisibilityFlags = "Should only set visibility flags when creating EnumBuilder.";
+	public const string Argument_SigIsFinalized = "Completed signature cannot be modified.";
+	public const string Argument_StreamNotReadable = "Stream was not readable.";
+	public const string Argument_StreamNotWritable = "Stream was not writable.";
+	public const string Argument_StringFirstCharIsZero = "The first char in the string is the null character.";
+	public const string Argument_StringZeroLength = "String cannot be of zero length.";
+	public const string Argument_StructMustNotBeValueClass = "The structure must not be a value class.";
+	public const string Argument_TimeSpanHasSeconds = "The TimeSpan parameter cannot be specified more precisely than whole minutes.";
+	public const string Argument_TimeZoneInfoBadTZif = "The tzfile does not begin with the magic characters 'TZif'.  Please verify that the file is not corrupt.";
+	public const string Argument_TimeZoneInfoInvalidTZif = "The TZif data structure is corrupt.";
+	public const string Argument_ToExclusiveLessThanFromExclusive = "fromInclusive must be less than or equal to toExclusive.";
+	public const string Argument_TooManyFinallyClause = "Exception blocks may have at most one finally clause.";
+	public const string Argument_TransitionTimesAreIdentical = "The DaylightTransitionStart property must not equal the DaylightTransitionEnd property.";
+	public const string Argument_TypedReferenceInvalidField = "Field '{0}' in TypedReferences cannot be static.";
+	public const string Argument_TypeIsWinRTType = "The type must not be a Windows Runtime type.";
+	public const string Argument_TypeMustBeVisibleFromCom = "The specified type must be visible from COM.";
+	public const string Argument_TypeMustNotBeComImport = "The type must not be imported from COM.";
+	public const string Argument_TypeNameTooLong = "Type name was too long. The fully qualified type name must be less than 1,024 characters.";
+	public const string Argument_TypeNotActivatableViaWindowsRuntime = "Type '{0}' does not have an activation factory because it is not activatable by Windows Runtime.";
+	public const string Argument_TypeNotComObject = "The type must be __ComObject or be derived from __ComObject.";
+	public const string Argument_TypeNotValid = "The Type object is not valid.";
+	public const string Argument_UnclosedExceptionBlock = "The IL Generator cannot be used while there are unclosed exceptions.";
+	public const string Argument_Unexpected_TypeSource = "Unexpected TypeKind when marshaling Windows.Foundation.TypeName.";
+	public const string Argument_UnknownUnmanagedCallConv = "Unknown unmanaged calling convention for function signature.";
+	public const string Argument_UnmanagedMemAccessorWrapAround = "The UnmanagedMemoryAccessor capacity and offset would wrap around the high end of the address space.";
+	public const string Argument_UnmatchedMethodForLocal = "Local passed in does not belong to this ILGenerator.";
+	public const string Argument_UnmatchingSymScope = "Non-matching symbol scope.";
+	public const string Argument_UTCOutOfRange = "The UTC time represented when the offset is applied must be between year 0 and 10,000.";
+	public const string Argument_VerStringTooLong = "The unmanaged Version information is too large to persist.";
+	public const string Argument_WaitHandleNameTooLong = "The length of the name exceeds the maximum limit.";
+	public const string Argument_WinRTSystemRuntimeType = "Cannot marshal type '{0}' to Windows Runtime. Only 'System.RuntimeType' is supported.";
+	public const string ArgumentException_BadMethodImplBody = "MethodOverride's body must be from this type.";
+	public const string ArgumentException_BufferNotFromPool = "The buffer is not associated with this pool and may not be returned to it.";
+	public const string ArgumentException_OtherNotArrayOfCorrectLength = "Object is not a array with the same number of elements as the array to compare it to.";
+	public const string ArgumentException_TupleIncorrectType = "Argument must be of type {0}.";
+	public const string ArgumentException_TupleLastArgumentNotATuple = "The last element of an eight element tuple must be a Tuple.";
+	public const string ArgumentException_ValueTupleIncorrectType = "Argument must be of type {0}.";
+	public const string ArgumentException_ValueTupleLastArgumentNotAValueTuple = "The last element of an eight element ValueTuple must be a ValueTuple.";
+	public const string ArgumentNull_Array = "Array cannot be null.";
+	public const string ArgumentNull_ArrayElement = "At least one element in the specified array was null.";
+	public const string ArgumentNull_ArrayValue = "Found a null value within an array.";
+	public const string ArgumentNull_Assembly = "Assembly cannot be null.";
+	public const string ArgumentNull_AssemblyName = "AssemblyName cannot be null.";
+	public const string ArgumentNull_AssemblyNameName = "AssemblyName.Name cannot be null or an empty string.";
+	public const string ArgumentNull_Buffer = "Buffer cannot be null.";
+	public const string ArgumentNull_Collection = "Collection cannot be null.";
+	public const string ArgumentNull_Dictionary = "Dictionary cannot be null.";
+	public const string ArgumentNull_FileName = "File name cannot be null.";
+	public const string ArgumentNull_Generic = "Value cannot be null.";
+	public const string ArgumentNull_GUID = "GUID cannot be null.";
+	public const string ArgumentNull_Key = "Key cannot be null.";
+	public const string ArgumentNull_Path = "Path cannot be null.";
+	public const string ArgumentNull_SafeHandle = "SafeHandle cannot be null.";
+	public const string ArgumentNull_Stream = "Stream cannot be null.";
+	public const string ArgumentNull_String = "String reference not set to an instance of a String.";
+	public const string ArgumentNull_Type = "Type cannot be null.";
+	public const string ArgumentNull_TypedRefType = "Type in TypedReference cannot be null.";
+	public const string ArgumentNull_Waithandles = "The waitHandles parameter cannot be null.";
+	public const string ArgumentOutOfRange_ActualValue = "Actual value was {0}.";
+	public const string ArgumentOutOfRange_AddressSpace = "The number of bytes cannot exceed the virtual address space on a 32 bit machine.";
+	public const string ArgumentOutOfRange_AddValue = "Value to add was out of range.";
+	public const string ArgumentOutOfRange_ArrayLB = "Number was less than the array's lower bound in the first dimension.";
+	public const string ArgumentOutOfRange_ArrayLBAndLength = "Higher indices will exceed Int32.MaxValue because of large lower bound and/or length.";
+	public const string ArgumentOutOfRange_BadHourMinuteSecond = "Hour, Minute, and Second parameters describe an un-representable DateTime.";
+	public const string ArgumentOutOfRange_BadYearMonthDay = "Year, Month, and Day parameters describe an un-representable DateTime.";
+	public const string ArgumentOutOfRange_BiggerThanCollection = "Larger than collection size.";
+	public const string ArgumentOutOfRange_BinaryReaderFillBuffer = "The number of bytes requested does not fit into BinaryReader's internal buffer.";
+	public const string ArgumentOutOfRange_Bounds_Lower_Upper = "Argument must be between {0} and {1}.";
+	public const string ArgumentOutOfRange_CalendarRange = "Specified time is not supported in this calendar. It should be between {0} (Gregorian date) and {1} (Gregorian date), inclusive.";
+	public const string ArgumentOutOfRange_Capacity = "Capacity exceeds maximum capacity.";
+	public const string ArgumentOutOfRange_Count = "Count must be positive and count must refer to a location within the string/array/collection.";
+	public const string ArgumentOutOfRange_DateArithmetic = "The added or subtracted value results in an un-representable DateTime.";
+	public const string ArgumentOutOfRange_DateTimeBadMonths = "Months value must be between +/-120000.";
+	public const string ArgumentOutOfRange_DateTimeBadTicks = "Ticks must be between DateTime.MinValue.Ticks and DateTime.MaxValue.Ticks.";
+	public const string ArgumentOutOfRange_DateTimeBadYears = "Years value must be between +/-10000.";
+	public const string ArgumentOutOfRange_Day = "Day must be between 1 and {0} for month {1}.";
+	public const string ArgumentOutOfRange_DayOfWeek = "The DayOfWeek enumeration must be in the range 0 through 6.";
+	public const string ArgumentOutOfRange_DayParam = "The Day parameter must be in the range 1 through 31.";
+	public const string ArgumentOutOfRange_DecimalRound = "Decimal can only round to between 0 and 28 digits of precision.";
+	public const string ArgumentOutOfRange_DecimalScale = "Decimal's scale value must be between 0 and 28, inclusive.";
+	public const string ArgumentOutOfRange_EndIndexStartIndex = "endIndex cannot be greater than startIndex.";
+	public const string ArgumentOutOfRange_Enum = "Enum value was out of legal range.";
+	public const string ArgumentOutOfRange_Era = "Time value was out of era range.";
+	public const string ArgumentOutOfRange_FileLengthTooBig = "Specified file length was too large for the file system.";
+	public const string ArgumentOutOfRange_FileTimeInvalid = "Not a valid Win32 FileTime.";
+	public const string ArgumentOutOfRange_GenericPositive = "Value must be positive.";
+	public const string ArgumentOutOfRange_GetByteCountOverflow = "Too many characters. The resulting number of bytes is larger than what can be returned as an int.";
+	public const string ArgumentOutOfRange_GetCharCountOverflow = "Too many bytes. The resulting number of chars is larger than what can be returned as an int.";
+	public const string ArgumentOutOfRange_HashtableLoadFactor = "Load factor needs to be between 0.1 and 1.0.";
+	public const string ArgumentOutOfRange_HugeArrayNotSupported = "Arrays larger than 2GB are not supported.";
+	public const string ArgumentOutOfRange_Index = "Index was out of range. Must be non-negative and less than the size of the collection.";
+	public const string ArgumentOutOfRange_IndexCount = "Index and count must refer to a location within the string.";
+	public const string ArgumentOutOfRange_IndexCountBuffer = "Index and count must refer to a location within the buffer.";
+	public const string ArgumentOutOfRange_IndexLargerThanMaxValue = "This collection cannot work with indices larger than Int32.MaxValue - 1 (0x7FFFFFFF - 1).";
+	public const string ArgumentOutOfRange_IndexLength = "Index and length must refer to a location within the string.";
+	public const string ArgumentOutOfRange_IndexString = "Index was out of range. Must be non-negative and less than the length of the string.";
+	public const string ArgumentOutOfRange_InvalidEraValue = "Era value was not valid.";
+	public const string ArgumentOutOfRange_InvalidHighSurrogate = "A valid high surrogate character is between 0xd800 and 0xdbff, inclusive.";
+	public const string ArgumentOutOfRange_InvalidLowSurrogate = "A valid low surrogate character is between 0xdc00 and 0xdfff, inclusive.";
+	public const string ArgumentOutOfRange_InvalidUTF32 = "A valid UTF32 value is between 0x000000 and 0x10ffff, inclusive, and should not include surrogate codepoint values (0x00d800 ~ 0x00dfff).";
+	public const string ArgumentOutOfRange_Length = "The specified length exceeds maximum capacity of SecureString.";
+	public const string ArgumentOutOfRange_LengthGreaterThanCapacity = "The length cannot be greater than the capacity.";
+	public const string ArgumentOutOfRange_LengthTooLarge = "The specified length exceeds the maximum value of {0}.";
+	public const string ArgumentOutOfRange_LessEqualToIntegerMaxVal = "Argument must be less than or equal to 2^31 - 1 milliseconds.";
+	public const string ArgumentOutOfRange_ListInsert = "Index must be within the bounds of the List.";
+	public const string ArgumentOutOfRange_Month = "Month must be between one and twelve.";
+	public const string ArgumentOutOfRange_MonthParam = "The Month parameter must be in the range 1 through 12.";
+	public const string ArgumentOutOfRange_MustBeNonNegInt32 = "Value must be non-negative and less than or equal to Int32.MaxValue.";
+	public const string ArgumentOutOfRange_MustBeNonNegNum = "'{0}' must be non-negative.";
+	public const string ArgumentOutOfRange_MustBePositive = "'{0}' must be greater than zero.";
+	public const string ArgumentOutOfRange_NeedNonNegNum = "Non-negative number required.";
+	public const string ArgumentOutOfRange_NeedNonNegOrNegative1 = "Number must be either non-negative and less than or equal to Int32.MaxValue or -1.";
+	public const string ArgumentOutOfRange_NeedPosNum = "Positive number required.";
+	public const string ArgumentOutOfRange_NeedValidId = "The ID parameter must be in the range {0} through {1}.";
+	public const string ArgumentOutOfRange_NegativeCapacity = "Capacity must be positive.";
+	public const string ArgumentOutOfRange_NegativeCount = "Count cannot be less than zero.";
+	public const string ArgumentOutOfRange_NegativeLength = "Length cannot be less than zero.";
+	public const string ArgumentOutOfRange_OffsetLength = "Offset and length must refer to a position in the string.";
+	public const string ArgumentOutOfRange_OffsetOut = "Either offset did not refer to a position in the string, or there is an insufficient length of destination character array.";
+	public const string ArgumentOutOfRange_ParamSequence = "The specified parameter index is not in range.";
+	public const string ArgumentOutOfRange_PartialWCHAR = "Pointer startIndex and length do not refer to a valid string.";
+	public const string ArgumentOutOfRange_PeriodTooLarge = "Period must be less than 2^32-2.";
+	public const string ArgumentOutOfRange_PositionLessThanCapacityRequired = "The position may not be greater or equal to the capacity of the accessor.";
+	public const string ArgumentOutOfRange_Range = "Valid values are between {0} and {1}, inclusive.";
+	public const string ArgumentOutOfRange_RoundingDigits = "Rounding digits must be between 0 and 15, inclusive.";
+	public const string ArgumentOutOfRange_SmallCapacity = "capacity was less than the current size.";
+	public const string ArgumentOutOfRange_SmallMaxCapacity = "MaxCapacity must be one or greater.";
+	public const string ArgumentOutOfRange_StartIndex = "StartIndex cannot be less than zero.";
+	public const string ArgumentOutOfRange_StartIndexLargerThanLength = "startIndex cannot be larger than length of string.";
+	public const string ArgumentOutOfRange_StartIndexLessThanLength = "startIndex must be less than length of string.";
+	public const string ArgumentOutOfRange_StreamLength = "Stream length must be non-negative and less than 2^31 - 1 - origin.";
+	public const string ArgumentOutOfRange_TimeoutTooLarge = "Time-out interval must be less than 2^32-2.";
+	public const string ArgumentOutOfRange_UIntPtrMax = "The length of the buffer must be less than the maximum UIntPtr value for your platform.";
+	public const string ArgumentOutOfRange_UnmanagedMemStreamLength = "UnmanagedMemoryStream length must be non-negative and less than 2^63 - 1 - baseAddress.";
+	public const string ArgumentOutOfRange_UnmanagedMemStreamWrapAround = "The UnmanagedMemoryStream capacity would wrap around the high end of the address space.";
+	public const string ArgumentOutOfRange_UtcOffset = "The TimeSpan parameter must be within plus or minus 14.0 hours.";
+	public const string ArgumentOutOfRange_UtcOffsetAndDaylightDelta = "The sum of the BaseUtcOffset and DaylightDelta properties must within plus or minus 14.0 hours.";
+	public const string ArgumentOutOfRange_Version = "Version's parameters must be greater than or equal to zero.";
+	public const string ArgumentOutOfRange_Week = "The Week parameter must be in the range 1 through 5.";
+	public const string ArgumentOutOfRange_Year = "Year must be between 1 and 9999.";
+	public const string Arithmetic_NaN = "Function does not accept floating point Not-a-Number values.";
+	public const string ArrayTypeMismatch_CantAssignType = "Source array type cannot be assigned to destination array type.";
+	public const string ArrayTypeMismatch_ConstrainedCopy = "Array.ConstrainedCopy will only work on array types that are provably compatible, without any form of boxing, unboxing, widening, or casting of each array element.  Change the array types (i.e., copy a Derived[] to a Base[]), or use a mitigation strategy in the CER for Array.Copy's less powerful reliability contract, such as cloning the array or throwing away the potentially corrupt destination array.";
+	public const string AssemblyLoadContext_Constructor_CannotInstantiateWhileUnloading = "Cannot instantiate AssemblyLoadContext while the current process is exiting.";
+	public const string AssemblyLoadContext_Unload_CannotUnloadIfNotCollectible = "Cannot unload non-collectible AssemblyLoadContext.";
+	public const string AssemblyLoadContext_Unload_AlreadyUnloaded = "Unload called on AssemblyLoadContext that is unloading or that was already unloaded.";
+	public const string AssemblyLoadContext_Verify_NotUnloading = "AssemblyLoadContext is unloading or was already unloaded.";
+	public const string AssertionFailed = "Assertion failed.";
+	public const string AssertionFailed_Cnd = "Assertion failed: {0}";
+	public const string AssumptionFailed = "Assumption failed.";
+	public const string AssumptionFailed_Cnd = "Assumption failed: {0}";
+	public const string AsyncMethodBuilder_InstanceNotInitialized = "The builder was not properly initialized.";
+	public const string BadImageFormat_BadILFormat = "Bad IL format.";
+	public const string BadImageFormat_InvalidType = "Corrupt .resources file.  The specified type doesn't exist.";
+	public const string BadImageFormat_NegativeStringLength = "Corrupt .resources file. String length must be non-negative.";
+	public const string BadImageFormat_ParameterSignatureMismatch = "The parameters and the signature of the method don't match.";
+	public const string BadImageFormat_ResType_SerBlobMismatch = "The type serialized in the .resources file was not the same type that the .resources file said it contained. Expected '{0}' but read '{1}'.";
+	public const string BadImageFormat_ResourceDataLengthInvalid = "Corrupt .resources file.  The specified data length '{0}' is not a valid position in the stream.";
+	public const string BadImageFormat_ResourceNameCorrupted = "Corrupt .resources file. A resource name extends past the end of the stream.";
+	public const string BadImageFormat_ResourceNameCorrupted_NameIndex = "Corrupt .resources file. The resource name for name index {0} extends past the end of the stream.";
+	public const string BadImageFormat_ResourcesDataInvalidOffset = "Corrupt .resources file. Invalid offset '{0}' into data section.";
+	public const string BadImageFormat_ResourcesHeaderCorrupted = "Corrupt .resources file. Unable to read resources from this file because of invalid header information. Try regenerating the .resources file.";
+	public const string BadImageFormat_ResourcesIndexTooLong = "Corrupt .resources file. String for name index '{0}' extends past the end of the file.";
+	public const string BadImageFormat_ResourcesNameInvalidOffset = "Corrupt .resources file. Invalid offset '{0}' into name section.";
+	public const string BadImageFormat_ResourcesNameTooLong = "Corrupt .resources file. Resource name extends past the end of the file.";
+	public const string BadImageFormat_TypeMismatch = "Corrupt .resources file.  The specified type doesn't match the available data in the stream.";
+	public const string CancellationToken_CreateLinkedToken_TokensIsEmpty = "No tokens were supplied.";
+	public const string CancellationToken_SourceDisposed = "The CancellationTokenSource associated with this CancellationToken has been disposed.";
+	public const string CancellationTokenSource_Disposed = "The CancellationTokenSource has been disposed.";
+	public const string ConcurrentCollection_SyncRoot_NotSupported = "The SyncRoot property may not be used for the synchronization of concurrent collections.";
+	public const string event_SpinLock_FastPathFailed = "SpinLock beginning to spin.";
+	public const string event_SpinWait_NextSpinWillYield = "Next spin will yield.";
+	public const string event_TaskCompleted = "Task {2} completed.";
+	public const string event_TaskScheduled = "Task {2} scheduled to TaskScheduler {0}.";
+	public const string event_TaskStarted = "Task {2} executing.";
+	public const string event_TaskWaitBegin = "Beginning wait ({3}) on Task {2}.";
+	public const string event_TaskWaitEnd = "Ending wait on Task {2}.";
+	public const string EventSource_AbstractMustNotDeclareEventMethods = "Abstract event source must not declare event methods ({0} with ID {1}).";
+	public const string EventSource_AbstractMustNotDeclareKTOC = "Abstract event source must not declare {0} nested type.";
+	public const string EventSource_AddScalarOutOfRange = "Getting out of bounds during scalar addition.";
+	public const string EventSource_BadHexDigit = "Bad Hexidecimal digit \"{0}\".";
+	public const string EventSource_ChannelTypeDoesNotMatchEventChannelValue = "Channel {0} does not match event channel value {1}.";
+	public const string EventSource_DataDescriptorsOutOfRange = "Data descriptors are out of range.";
+	public const string EventSource_DuplicateStringKey = "Multiple definitions for string \"{0}\".";
+	public const string EventSource_EnumKindMismatch = "The type of {0} is not expected in {1}.";
+	public const string EventSource_EvenHexDigits = "Must have an even number of Hexidecimal digits.";
+	public const string EventSource_EventChannelOutOfRange = "Channel {0} has a value of {1} which is outside the legal range (16-254).";
+	public const string EventSource_EventIdReused = "Event {0} has ID {1} which is already in use.";
+	public const string EventSource_EventMustHaveTaskIfNonDefaultOpcode = "Event {0} (with ID {1}) has a non-default opcode but not a task.";
+	public const string EventSource_EventMustNotBeExplicitImplementation = "Event method {0} (with ID {1}) is an explicit interface method implementation. Re-write method as implicit implementation.";
+	public const string EventSource_EventNameDoesNotEqualTaskPlusOpcode = "Event {0} (with ID {1}) has a name that is not the concatenation of its task name and opcode.";
+	public const string EventSource_EventNameReused = "Event name {0} used more than once.  If you wish to overload a method, the overloaded method should have a NonEvent attribute.";
+	public const string EventSource_EventParametersMismatch = "Event {0} was called with {1} argument(s), but it is defined with {2} parameter(s).";
+	public const string EventSource_EventSourceGuidInUse = "An instance of EventSource with Guid {0} already exists.";
+	public const string EventSource_EventTooBig = "The payload for a single event is too large.";
+	public const string EventSource_EventWithAdminChannelMustHaveMessage = "Event {0} specifies an Admin channel {1}. It must specify a Message property.";
+	public const string EventSource_IllegalKeywordsValue = "Keyword {0} has a value of {1} which is outside the legal range (0-0x0000080000000000).";
+	public const string EventSource_IllegalOpcodeValue = "Opcode {0} has a value of {1} which is outside the legal range (11-238).";
+	public const string EventSource_IllegalTaskValue = "Task {0} has a value of {1} which is outside the legal range (1-65535).";
+	public const string EventSource_IllegalValue = "Illegal value \"{0}\" (prefix strings with @ to indicate a literal string).";
+	public const string EventSource_IncorrentlyAuthoredTypeInfo = "Incorrectly-authored TypeInfo - a type should be serialized as one field or as one group";
+	public const string EventSource_InvalidCommand = "Invalid command value.";
+	public const string EventSource_InvalidEventFormat = "Can't specify both etw event format flags.";
+	public const string EventSource_KeywordCollision = "Keywords {0} and {1} are defined with the same value ({2}).";
+	public const string EventSource_KeywordNeedPowerOfTwo = "Value {0} for keyword {1} needs to be a power of 2.";
+	public const string EventSource_ListenerCreatedInsideCallback = "Creating an EventListener inside a EventListener callback.";
+	public const string EventSource_ListenerNotFound = "Listener not found.";
+	public const string EventSource_ListenerWriteFailure = "An error occurred when writing to a listener.";
+	public const string EventSource_MaxChannelExceeded = "Attempt to define more than the maximum limit of 8 channels for a provider.";
+	public const string EventSource_MismatchIdToWriteEvent = "Event {0} was assigned event ID {1} but {2} was passed to WriteEvent.";
+	public const string EventSource_NeedGuid = "The Guid of an EventSource must be non zero.";
+	public const string EventSource_NeedName = "The name of an EventSource must not be null.";
+	public const string EventSource_NeedPositiveId = "Event IDs must be positive integers.";
+	public const string EventSource_NoFreeBuffers = "No Free Buffers available from the operating system (e.g. event rate too fast).";
+	public const string EventSource_NonCompliantTypeError = "The API supports only anonymous types or types decorated with the EventDataAttribute. Non-compliant type: {0} dataType.";
+	public const string EventSource_NoRelatedActivityId = "EventSource expects the first parameter of the Event method to be of type Guid and to be named \"relatedActivityId\" when calling WriteEventWithRelatedActivityId.";
+	public const string EventSource_NotSupportedArrayOfBinary = "Arrays of Binary are not supported.";
+	public const string EventSource_NotSupportedArrayOfNil = "Arrays of Nil are not supported.";
+	public const string EventSource_NotSupportedArrayOfNullTerminatedString = "Arrays of null-terminated string are not supported.";
+	public const string EventSource_NotSupportedCustomSerializedData = "Enumerables of custom-serialized data are not supported";
+	public const string EventSource_NotSupportedNestedArraysEnums = "Nested arrays/enumerables are not supported.";
+	public const string EventSource_NullInput = "Null passed as a event argument.";
+	public const string EventSource_OpcodeCollision = "Opcodes {0} and {1} are defined with the same value ({2}).";
+	public const string EventSource_PinArrayOutOfRange = "Pins are out of range.";
+	public const string EventSource_RecursiveTypeDefinition = "Recursive type definition is not supported.";
+	public const string EventSource_SessionIdError = "Bit position in AllKeywords ({0}) must equal the command argument named \"EtwSessionKeyword\" ({1}).";
+	public const string EventSource_StopsFollowStarts = "An event with stop suffix must follow a corresponding event with a start suffix.";
+	public const string EventSource_TaskCollision = "Tasks {0} and {1} are defined with the same value ({2}).";
+	public const string EventSource_TaskOpcodePairReused = "Event {0} (with ID {1}) has the same task/opcode pair as event {2} (with ID {3}).";
+	public const string EventSource_TooManyArgs = "Too many arguments.";
+	public const string EventSource_TooManyFields = "Too many fields in structure.";
+	public const string EventSource_ToString = "EventSource({0}, {1})";
+	public const string EventSource_TraitEven = "There must be an even number of trait strings (they are key-value pairs).";
+	public const string EventSource_TypeMustBeSealedOrAbstract = "Event source types must be sealed or abstract.";
+	public const string EventSource_TypeMustDeriveFromEventSource = "Event source types must derive from EventSource.";
+	public const string EventSource_UndefinedChannel = "Use of undefined channel value {0} for event {1}.";
+	public const string EventSource_UndefinedKeyword = "Use of undefined keyword value {0} for event {1}.";
+	public const string EventSource_UndefinedOpcode = "Use of undefined opcode value {0} for event {1}.";
+	public const string EventSource_UnknownEtwTrait = "Unknown ETW trait \"{0}\".";
+	public const string EventSource_UnsupportedEventTypeInManifest = "Unsupported type {0} in event source.";
+	public const string EventSource_UnsupportedMessageProperty = "Event {0} specifies an illegal or unsupported formatting message (\"{1}\").";
+	public const string EventSource_VarArgsParameterMismatch = "The parameters to the Event method do not match the parameters to the WriteEvent method. This may cause the event to be displayed incorrectly.";
+	public const string Exception_EndOfInnerExceptionStack = "--- End of inner exception stack trace ---";
+	public const string Exception_EndStackTraceFromPreviousThrow = "--- End of stack trace from previous location where exception was thrown ---";
+	public const string Exception_WasThrown = "Exception of type '{0}' was thrown.";
+	public const string ExecutionContext_ExceptionInAsyncLocalNotification = "An exception was not handled in an AsyncLocal<T> notification callback.";
+	public const string FieldAccess_InitOnly = "InitOnly (aka ReadOnly) fields can only be initialized in the type/instance constructor.";
+	public const string FileNotFound_ResolveAssembly = "Could not resolve assembly '{0}'.";
+	public const string Format_AttributeUsage = "Duplicate AttributeUsageAttribute found on attribute type {0}.";
+	public const string Format_Bad7BitInt32 = "Too many bytes in what should have been a 7 bit encoded Int32.";
+	public const string Format_BadBase = "Invalid digits for the specified base.";
+	public const string Format_BadBase64Char = "The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.";
+	public const string Format_BadBase64CharArrayLength = "Invalid length for a Base-64 char array or string.";
+	public const string Format_BadBoolean = "String '{0}' was not recognized as a valid Boolean.";
+	public const string Format_BadDatePattern = "Could not determine the order of year, month, and date from '{0}'.";
+	public const string Format_BadDateTime = "String '{0}' was not recognized as a valid DateTime.";
+	public const string Format_BadDateTimeCalendar = "The DateTime represented by the string '{0}' is not supported in calendar '{1}'.";
+	public const string Format_BadDayOfWeek = "String '{0}' was not recognized as a valid DateTime because the day of week was incorrect.";
+	public const string Format_BadFormatSpecifier = "Format specifier '{0}' was invalid.";
+	public const string Format_NoFormatSpecifier = "No format specifiers were provided.";
+	public const string Format_BadQuote = "Cannot find a matching quote character for the character '{0}'.";
+	public const string Format_BadTimeSpan = "String '{0}' was not recognized as a valid TimeSpan.";
+	public const string Format_DateOutOfRange = "The DateTime represented by the string '{0}' is out of range.";
+	public const string Format_EmptyInputString = "Input string was either empty or contained only whitespace.";
+	public const string Format_ExtraJunkAtEnd = "Additional non-parsable characters are at the end of the string.";
+	public const string Format_GuidBrace = "Expected {0xdddddddd, etc}.";
+	public const string Format_GuidBraceAfterLastNumber = "Could not find a brace, or the length between the previous token and the brace was zero (i.e., '0x,'etc.).";
+	public const string Format_GuidComma = "Could not find a comma, or the length between the previous token and the comma was zero (i.e., '0x,'etc.).";
+	public const string Format_GuidDashes = "Dashes are in the wrong position for GUID parsing.";
+	public const string Format_GuidEndBrace = "Could not find the ending brace.";
+	public const string Format_GuidHexPrefix = "Expected 0x prefix.";
+	public const string Format_GuidInvalidChar = "Guid string should only contain hexadecimal characters.";
+	public const string Format_GuidInvLen = "Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).";
+	public const string Format_GuidUnrecognized = "Unrecognized Guid format.";
+	public const string Format_IndexOutOfRange = "Index (zero based) must be greater than or equal to zero and less than the size of the argument list.";
+	public const string Format_InvalidEnumFormatSpecification = "Format string can be only \"G\", \"g\", \"X\", \"x\", \"F\", \"f\", \"D\" or \"d\".";
+	public const string Format_InvalidGuidFormatSpecification = "Format string can be only \"D\", \"d\", \"N\", \"n\", \"P\", \"p\", \"B\", \"b\", \"X\" or \"x\".";
+	public const string Format_InvalidString = "Input string was not in a correct format.";
+	public const string Format_MissingIncompleteDate = "There must be at least a partial date with a year present in the input string '{0}'.";
+	public const string Format_NeedSingleChar = "String must be exactly one character long.";
+	public const string Format_NoParsibleDigits = "Could not find any recognizable digits.";
+	public const string Format_OffsetOutOfRange = "The time zone offset of string '{0}' must be within plus or minus 14 hours.";
+	public const string Format_RepeatDateTimePattern = "DateTime pattern '{0}' appears more than once with different values.";
+	public const string Format_StringZeroLength = "String cannot have zero length.";
+	public const string Format_UnknownDateTimeWord = "The string '{0}' was not recognized as a valid DateTime. There is an unknown word starting at index '{1}'.";
+	public const string Format_UTCOutOfRange = "The UTC representation of the date '{0}' falls outside the year range 1-9999.";
+	public const string Globalization_cp_1200 = "Unicode";
+	public const string Globalization_cp_12000 = "Unicode (UTF-32)";
+	public const string Globalization_cp_12001 = "Unicode (UTF-32 Big-Endian)";
+	public const string Globalization_cp_1201 = "Unicode (Big-Endian)";
+	public const string Globalization_cp_20127 = "US-ASCII";
+	public const string Globalization_cp_28591 = "Western European (ISO)";
+	public const string Globalization_cp_65000 = "Unicode (UTF-7)";
+	public const string Globalization_cp_65001 = "Unicode (UTF-8)";
+	public const string IndexOutOfRange_ArrayRankIndex = "Array does not have that many dimensions.";
+	public const string IndexOutOfRange_UMSPosition = "Unmanaged memory stream position was beyond the capacity of the stream.";
+	public const string InsufficientMemory_MemFailPoint = "Insufficient available memory to meet the expected demands of an operation at this time.  Please try again later.";
+	public const string InsufficientMemory_MemFailPoint_TooBig = "Insufficient memory to meet the expected demands of an operation, and this system is likely to never satisfy this request.  If this is a 32 bit system, consider booting in 3 GB mode.";
+	public const string InsufficientMemory_MemFailPoint_VAFrag = "Insufficient available memory to meet the expected demands of an operation at this time, possibly due to virtual address space fragmentation.  Please try again later.";
+	public const string Interop_COM_TypeMismatch = "Type mismatch between source and destination types.";
+	public const string Interop_Marshal_Unmappable_Char = "Cannot marshal: Encountered unmappable character.";
+	public const string InvalidCast_CannotCastNullToValueType = "Null object cannot be converted to a value type.";
+	public const string InvalidCast_CannotCoerceByRefVariant = "Object cannot be coerced to the original type of the ByRef VARIANT it was obtained from.";
+	public const string InvalidCast_DBNull = "Object cannot be cast to DBNull.";
+	public const string InvalidCast_DownCastArrayElement = "At least one element in the source array could not be cast down to the destination array type.";
+	public const string InvalidCast_Empty = "Object cannot be cast to Empty.";
+	public const string InvalidCast_FromDBNull = "Object cannot be cast from DBNull to other types.";
+	public const string InvalidCast_FromTo = "Invalid cast from '{0}' to '{1}'.";
+	public const string InvalidCast_IConvertible = "Object must implement IConvertible.";
+	public const string InvalidCast_OATypeMismatch = "OleAut reported a type mismatch.";
+	public const string InvalidCast_StoreArrayElement = "Object cannot be stored in an array of this type.";
+	public const string InvalidCast_WinRTIPropertyValueArrayCoersion = "Object in an IPropertyValue is of type '{0}' which cannot be convereted to a '{1}' due to array element '{2}': {3}.";
+	public const string InvalidCast_WinRTIPropertyValueCoersion = "Object in an IPropertyValue is of type '{0}' with value '{1}', which cannot be converted to a '{2}'.";
+	public const string InvalidCast_WinRTIPropertyValueElement = "Object in an IPropertyValue is of type '{0}', which cannot be converted to a '{1}'.";
+	public const string InvalidOperation_AsyncFlowCtrlCtxMismatch = "AsyncFlowControl objects can be used to restore flow only on a Context that had its flow suppressed.";
+	public const string InvalidOperation_AsyncIOInProgress = "The stream is currently in use by a previous operation on the stream.";
+	public const string InvalidOperation_BadEmptyMethodBody = "Method '{0}' does not have a method body.";
+	public const string InvalidOperation_BadILGeneratorUsage = "ILGenerator usage is invalid.";
+	public const string InvalidOperation_BadInstructionOrIndexOutOfBound = "MSIL instruction is invalid or index is out of bounds.";
+	public const string InvalidOperation_BadInterfaceNotAbstract = "Interface must be declared abstract.";
+	public const string InvalidOperation_BadMethodBody = "Method '{0}' cannot have a method body.";
+	public const string InvalidOperation_BadTypeAttributesNotAbstract = "Type must be declared abstract if any of its methods are abstract.";
+	public const string InvalidOperation_CalledTwice = "The method cannot be called twice on the same instance.";
+	public const string InvalidOperation_CannotImportGlobalFromDifferentModule = "Unable to import a global method or field from a different module.";
+	public const string InvalidOperation_CannotRemoveLastFromEmptyCollection = "Cannot remove the last element from an empty collection.";
+	public const string InvalidOperation_CannotRestoreUnsupressedFlow = "Cannot restore context flow when it is not suppressed.";
+	public const string InvalidOperation_CannotSupressFlowMultipleTimes = "Context flow is already suppressed.";
+	public const string InvalidOperation_CannotUseAFCMultiple = "AsyncFlowControl object can be used only once to call Undo().";
+	public const string InvalidOperation_CannotUseAFCOtherThread = "AsyncFlowControl object must be used on the thread where it was created.";
+	public const string InvalidOperation_CantInstantiateAbstractClass = "Instances of abstract classes cannot be created.";
+	public const string InvalidOperation_CantInstantiateFunctionPointer = "Instances of function pointers cannot be created.";
+	public const string InvalidOperation_CollectionBackingDictionaryTooLarge = "The collection backing this Dictionary contains too many elements.";
+	public const string InvalidOperation_CollectionBackingListTooLarge = "The collection backing this List contains too many elements.";
+	public const string InvalidOperation_CollectionCorrupted = "A prior operation on this collection was interrupted by an exception. Collection's state is no longer trusted.";
+	public const string InvalidOperation_ConcurrentOperationsNotSupported = "Operations that change non-concurrent collections must have exclusive access. A concurrent update was performed on this collection and corrupted its state. The collection's state is no longer correct.";
+	public const string InvalidOperation_ConstructorNotAllowedOnInterface = "Interface cannot have constructors.";
+	public const string InvalidOperation_DateTimeParsing = "Internal Error in DateTime and Calendar operations.";
+	public const string InvalidOperation_DebuggerLaunchFailed = "Debugger unable to launch.";
+	public const string InvalidOperation_DefaultConstructorILGen = "Unable to access ILGenerator on a constructor created with DefineDefaultConstructor.";
+	public const string InvalidOperation_EndReadCalledMultiple = "EndRead can only be called once for each asynchronous operation.";
+	public const string InvalidOperation_EndWriteCalledMultiple = "EndWrite can only be called once for each asynchronous operation.";
+	public const string InvalidOperation_EnumEnded = "Enumeration already finished.";
+	public const string InvalidOperation_EnumFailedVersion = "Collection was modified; enumeration operation may not execute.";
+	public const string InvalidOperation_EnumNotStarted = "Enumeration has not started. Call MoveNext.";
+	public const string InvalidOperation_EnumOpCantHappen = "Enumeration has either not started or has already finished.";
+	public const string InvalidOperation_EventInfoNotAvailable = "This API does not support EventInfo tokens.";
+	public const string InvalidOperation_EventTokenTableRequiresDelegate = "Type '{0}' is not a delegate type.  EventTokenTable may only be used with delegate types.";
+	public const string InvalidOperation_GenericParametersAlreadySet = "The generic parameters are already defined on this MethodBuilder.";
+	public const string InvalidOperation_GetVersion = "OSVersion's call to GetVersionEx failed.";
+	public const string InvalidOperation_GlobalsHaveBeenCreated = "Type definition of the global function has been completed.";
+	public const string InvalidOperation_HandleIsNotInitialized = "Handle is not initialized.";
+	public const string InvalidOperation_HandleIsNotPinned = "Handle is not pinned.";
+	public const string InvalidOperation_HashInsertFailed = "Hashtable insert failed. Load factor too high. The most common cause is multiple threads writing to the Hashtable simultaneously.";
+	public const string InvalidOperation_IComparerFailed = "Failed to compare two elements in the array.";
+	public const string InvalidOperation_MethodBaked = "Type definition of the method is complete.";
+	public const string InvalidOperation_MethodBuilderBaked = "The signature of the MethodBuilder can no longer be modified because an operation on the MethodBuilder caused the methodDef token to be created. For example, a call to SetCustomAttribute requires the methodDef token to emit the CustomAttribute token.";
+	public const string InvalidOperation_MethodHasBody = "Method already has a body.";
+	public const string InvalidOperation_MustCallInitialize = "You must call Initialize on this object instance before using it.";
+	public const string InvalidOperation_NativeOverlappedReused = "NativeOverlapped cannot be reused for multiple operations.";
+	public const string InvalidOperation_NoMultiModuleAssembly = "You cannot have more than one dynamic module in each dynamic assembly in this version of the runtime.";
+	public const string InvalidOperation_NoPublicAddMethod = "Cannot add the event handler since no public add method exists for the event.";
+	public const string InvalidOperation_NoPublicRemoveMethod = "Cannot remove the event handler since no public remove method exists for the event.";
+	public const string InvalidOperation_NotADebugModule = "Not a debug ModuleBuilder.";
+	public const string InvalidOperation_NotAllowedInDynamicMethod = "The requested operation is invalid for DynamicMethod.";
+	public const string InvalidOperation_NotAVarArgCallingConvention = "Calling convention must be VarArgs.";
+	public const string InvalidOperation_NotGenericType = "This operation is only valid on generic types.";
+	public const string InvalidOperation_NotSupportedOnWinRTEvent = "Adding or removing event handlers dynamically is not supported on WinRT events.";
+	public const string InvalidOperation_NotWithConcurrentGC = "This API is not available when the concurrent GC is enabled.";
+	public const string InvalidOperation_NoUnderlyingTypeOnEnum = "Underlying type information on enumeration is not specified.";
+	public const string InvalidOperation_NoValue = "Nullable object must have a value.";
+	public const string InvalidOperation_NullArray = "The underlying array is null.";
+	public const string InvalidOperation_NullContext = "Cannot call Set on a null context";
+	public const string InvalidOperation_NullModuleHandle = "The requested operation is invalid when called on a null ModuleHandle.";
+	public const string InvalidOperation_OpenLocalVariableScope = "Local variable scope was not properly closed.";
+	public const string InvalidOperation_Overlapped_Pack = "Cannot pack a packed Overlapped again.";
+	public const string InvalidOperation_PropertyInfoNotAvailable = "This API does not support PropertyInfo tokens.";
+	public const string InvalidOperation_ReadOnly = "Instance is read-only.";
+	public const string InvalidOperation_ResMgrBadResSet_Type = "'{0}': ResourceSet derived classes must provide a constructor that takes a String file name and a constructor that takes a Stream.";
+	public const string InvalidOperation_ResourceNotStream_Name = "Resource '{0}' was not a Stream - call GetObject instead.";
+	public const string InvalidOperation_ResourceNotString_Name = "Resource '{0}' was not a String - call GetObject instead.";
+	public const string InvalidOperation_ResourceNotString_Type = "Resource was of type '{0}' instead of String - call GetObject instead.";
+	public const string InvalidOperation_SetData_OnlyOnce = "SetData can only be used to set the value of a given name once.";
+	public const string InvalidOperation_ShouldNotHaveMethodBody = "Method body should not exist.";
+	public const string InvalidOperation_ThreadWrongThreadStart = "The thread was created with a ThreadStart delegate that does not accept a parameter.";
+	public const string InvalidOperation_TimeoutsNotSupported = "Timeouts are not supported on this stream.";
+	public const string InvalidOperation_TimerAlreadyClosed = "The Timer was already closed using an incompatible Dispose method.";
+	public const string InvalidOperation_TypeCannotBeBoxed = "The given type cannot be boxed.";
+	public const string InvalidOperation_TypeHasBeenCreated = "Unable to change after type has been created.";
+	public const string InvalidOperation_TypeNotCreated = "Type has not been created.";
+	public const string InvalidOperation_UnknownEnumType = "Unknown enum type.";
+	public const string InvalidOperation_WriteOnce = "This property has already been set and cannot be modified.";
+	public const string InvalidOperation_WrongAsyncResultOrEndCalledMultiple = "Either the IAsyncResult object did not come from the corresponding async method on this type, or the End method was called multiple times with the same IAsyncResult.";
+	public const string InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple = "Either the IAsyncResult object did not come from the corresponding async method on this type, or EndRead was called multiple times with the same IAsyncResult.";
+	public const string InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple = "Either the IAsyncResult object did not come from the corresponding async method on this type, or EndWrite was called multiple times with the same IAsyncResult.";
+	public const string InvalidProgram_Default = "Common Language Runtime detected an invalid program.";
+	public const string InvalidTimeZone_InvalidFileData = "The time zone ID '{0}' was found on the local computer, but the file at '{1}' was corrupt.";
+	public const string InvalidTimeZone_InvalidRegistryData = "The time zone ID '{0}' was found on the local computer, but the registry information was corrupt.";
+	public const string InvalidTimeZone_InvalidJulianDay = "Invalid Julian day in POSIX strings.";
+	public const string InvalidTimeZone_NJulianDayNotSupported = "Julian n day in POSIX strings is not supported.";
+	public const string InvalidTimeZone_NoTTInfoStructures = "There are no ttinfo structures in the tzfile.  At least one ttinfo structure is required in order to construct a TimeZoneInfo object.";
+	public const string InvalidTimeZone_UnparseablePosixMDateString = "'{0}' is not a valid POSIX-TZ-environment-variable MDate rule.  A valid rule has the format 'Mm.w.d'.";
+	public const string InvariantFailed = "Invariant failed.";
+	public const string InvariantFailed_Cnd = "Invariant failed: {0}";
+	public const string IO_DriveNotFound_Drive = "Could not find the drive '{0}'. The drive might not be ready or might not be mapped.";
+	public const string IO_EOF_ReadBeyondEOF = "Unable to read beyond the end of the stream.";
+	public const string IO_FileLoad = "Could not load the specified file.";
+	public const string IO_FileName_Name = "File name: '{0}'";
+	public const string IO_FileNotFound = "Unable to find the specified file.";
+	public const string IO_FileNotFound_FileName = "Could not find file '{0}'.";
+	public const string IO_AlreadyExists_Name = "Cannot create '{0}' because a file or directory with the same name already exists.";
+	public const string IO_BindHandleFailed = "BindHandle for ThreadPool failed on this handle.";
+	public const string IO_FileExists_Name = "The file '{0}' already exists.";
+	public const string IO_FileStreamHandlePosition = "The OS handle's position is not what FileStream expected. Do not use a handle simultaneously in one FileStream and in Win32 code or another FileStream. This may cause data loss.";
+	public const string IO_FileTooLong2GB = "The file is too long. This operation is currently limited to supporting files less than 2 gigabytes in size.";
+	public const string IO_FileTooLongOrHandleNotSync = "IO operation will not work. Most likely the file will become too long or the handle was not opened to support synchronous IO operations.";
+	public const string IO_FixedCapacity = "Unable to expand length of this stream beyond its capacity.";
+	public const string IO_InvalidStringLen_Len = "BinaryReader encountered an invalid string length of {0} characters.";
+	public const string IO_SeekAppendOverwrite = "Unable seek backward to overwrite data that previously existed in a file opened in Append mode.";
+	public const string IO_SeekBeforeBegin = "An attempt was made to move the position before the beginning of the stream.";
+	public const string IO_SetLengthAppendTruncate = "Unable to truncate data that previously existed in a file opened in Append mode.";
+	public const string IO_SharingViolation_File = "The process cannot access the file '{0}' because it is being used by another process.";
+	public const string IO_SharingViolation_NoFileName = "The process cannot access the file because it is being used by another process.";
+	public const string IO_StreamTooLong = "Stream was too long.";
+	public const string IO_PathNotFound_NoPathName = "Could not find a part of the path.";
+	public const string IO_PathNotFound_Path = "Could not find a part of the path '{0}'.";
+	public const string IO_PathTooLong = "The specified file name or path is too long, or a component of the specified path is too long.";
+	public const string IO_PathTooLong_Path = "The path '{0}' is too long, or a component of the specified path is too long.";
+	public const string IO_UnknownFileName = "[Unknown]";
+	public const string Lazy_CreateValue_NoParameterlessCtorForT = "The lazily-initialized type does not have a public, parameterless constructor.";
+	public const string Lazy_ctor_ModeInvalid = "The mode argument specifies an invalid value.";
+	public const string Lazy_StaticInit_InvalidOperation = "ValueFactory returned null.";
+	public const string Lazy_ToString_ValueNotCreated = "Value is not created.";
+	public const string Lazy_Value_RecursiveCallsToValue = "ValueFactory attempted to access the Value property of this instance.";
+	public const string Loader_ContextPolicies = "Context Policies:";
+	public const string Loader_Name = "Name:";
+	public const string Loader_NoContextPolicies = "There are no context policies.";
+	public const string ManualResetEventSlim_ctor_SpinCountOutOfRange = "The spinCount argument must be in the range 0 to {0}, inclusive.";
+	public const string ManualResetEventSlim_ctor_TooManyWaiters = "There are too many threads currently waiting on the event. A maximum of {0} waiting threads are supported.";
+	public const string ManualResetEventSlim_Disposed = "The event has been disposed.";
+	public const string Marshaler_StringTooLong = "Marshaler restriction: Excessively long string.";
+	public const string MissingConstructor_Name = "Constructor on type '{0}' not found.";
+	public const string MissingField = "Field not found.";
+	public const string MissingField_Name = "Field '{0}' not found.";
+	public const string MissingManifestResource_LooselyLinked = "Could not find a manifest resource entry called \"{0}\" in assembly \"{1}\". Please check spelling, capitalization, and build rules to ensure \"{0}\" is being linked into the assembly.";
+	public const string MissingManifestResource_MultipleBlobs = "A case-insensitive lookup for resource file \"{0}\" in assembly \"{1}\" found multiple entries. Remove the duplicates or specify the exact case.";
+	public const string MissingManifestResource_NoNeutralAsm = "Could not find any resources appropriate for the specified culture or the neutral culture.  Make sure \"{0}\" was correctly embedded or linked into assembly \"{1}\" at compile time, or that all the satellite assemblies required are loadable and fully signed.";
+	public const string MissingManifestResource_NoNeutralDisk = "Could not find any resources appropriate for the specified culture (or the neutral culture) on disk.";
+	public const string MissingManifestResource_NoPRIresources = "Unable to open Package Resource Index.";
+	public const string MissingManifestResource_ResWFileNotLoaded = "Unable to load resources for resource file \"{0}\" in package \"{1}\".";
+	public const string MissingMember = "Member not found.";
+	public const string MissingMember_Name = "Member '{0}' not found.";
+	public const string MissingMemberNestErr = "TypedReference can only be made on nested value Types.";
+	public const string MissingMemberTypeRef = "FieldInfo does not match the target Type.";
+	public const string MissingMethod_Name = "Method '{0}' not found.";
+	public const string MissingSatelliteAssembly_Culture_Name = "The satellite assembly named \"{1}\" for fallback culture \"{0}\" either could not be found or could not be loaded. This is generally a setup problem. Please consider reinstalling or repairing the application.";
+	public const string MissingSatelliteAssembly_Default = "Resource lookup fell back to the ultimate fallback resources in a satellite assembly, but that satellite either was not found or could not be loaded. Please consider reinstalling or repairing the application.";
+	public const string Multicast_Combine = "Delegates that are not of type MulticastDelegate may not be combined.";
+	public const string MustUseCCRewrite = "An assembly (probably \"{1}\") must be rewritten using the code contracts binary rewriter (CCRewrite) because it is calling Contract.{0} and the CONTRACTS_FULL symbol is defined.  Remove any explicit definitions of the CONTRACTS_FULL symbol from your project and rebuild.  CCRewrite can be downloaded from http://go.microsoft.com/fwlink/?LinkID=169180. \\r\\nAfter the rewriter is installed, it can be enabled in Visual Studio from the project's Properties page on the Code Contracts pane.  Ensure that \"Perform Runtime Contract Checking\" is enabled, which will define CONTRACTS_FULL.";
+	public const string NotImplemented_ResourcesLongerThanInt64Max = "Resource files longer than 2^63 bytes are not currently implemented.";
+	public const string NotSupported_AbstractNonCLS = "This non-CLS method is not implemented.";
+	public const string NotSupported_ActivAttr = "Activation Attributes are not supported.";
+	public const string NotSupported_AppX = "{0} is not supported in AppX.";
+	public const string NotSupported_AssemblyLoadFromHash = "Assembly.LoadFrom with hashValue is not supported.";
+	public const string NotSupported_ByRefLike = "Cannot create boxed ByRef-like values.";
+	public const string NotSupported_ByRefLikeArray = "Cannot create arrays of ByRef-like values.";
+	public const string NotSupported_ByRefToByRefLikeReturn = "ByRef to ByRef-like return values are not supported in reflection invocation.";
+	public const string NotSupported_ByRefToVoidReturn = "ByRef to void return values are not supported in reflection invocation.";
+	public const string NotSupported_CallToVarArg = "Vararg calling convention not supported.";
+	public const string NotSupported_CannotCallEqualsOnSpan = "Equals() on Span and ReadOnlySpan is not supported. Use operator== instead.";
+	public const string NotSupported_CannotCallGetHashCodeOnSpan = "GetHashCode() on Span and ReadOnlySpan is not supported.";
+	public const string NotSupported_ChangeType = "ChangeType operation is not supported.";
+	public const string NotSupported_CollectibleAssemblyResolve = "Resolving to a collectible assembly is not supported.";
+	public const string NotSupported_CollectibleBoundNonCollectible = "A non-collectible assembly may not reference a collectible assembly.";
+	public const string NotSupported_CollectibleWinRT = "WinRT Interop is not supported for collectible types.";
+	public const string NotSupported_CreateInstanceWithTypeBuilder = "CreateInstance cannot be used with an object of type TypeBuilder.";
+	public const string NotSupported_DBNullSerial = "Only one DBNull instance may exist, and calls to DBNull deserialization methods are not allowed.";
+	public const string NotSupported_DelegateMarshalToWrongDomain = "Delegates cannot be marshaled from native code into a domain other than their home domain.";
+	public const string NotSupported_DelegateSerHolderSerial = "DelegateSerializationHolder objects are designed to represent a delegate during serialization and are not serializable themselves.";
+	public const string NotSupported_DynamicAssembly = "The invoked member is not supported in a dynamic assembly.";
+	public const string NotSupported_DynamicMethodFlags = "Wrong MethodAttributes or CallingConventions for DynamicMethod. Only public, static, standard supported";
+	public const string NotSupported_DynamicModule = "The invoked member is not supported in a dynamic module.";
+	public const string NotSupported_FileStreamOnNonFiles = "FileStream was asked to open a device that was not a file. For support for devices like 'com1:' or 'lpt1:', call CreateFile, then use the FileStream constructors that take an OS handle as an IntPtr.";
+	public const string NotSupported_FixedSizeCollection = "Collection was of a fixed size.";
+	public const string NotSupported_GenericMethod = "Generic methods with NativeCallableAttribute are not supported.";
+	public const string NotSupported_GlobalMethodSerialization = "Serialization of global methods (including implicit serialization via the use of asynchronous delegates) is not supported.";
+	public const string NotSupported_IDispInvokeDefaultMemberWithNamedArgs = "Invoking default method with named arguments is not supported.";
+	public const string NotSupported_IllegalOneByteBranch = "Illegal one-byte branch at position: {0}. Requested branch was: {1}.";
+	public const string NotSupported_KeyCollectionSet = "Mutating a key collection derived from a dictionary is not allowed.";
+	public const string NotSupported_ManagedActivation = "Cannot create uninitialized instances of types requiring managed activation.";
+	public const string NotSupported_MaxWaitHandles = "The number of WaitHandles must be less than or equal to 64.";
+	public const string NotSupported_MemStreamNotExpandable = "Memory stream is not expandable.";
+	public const string NotSupported_MustBeModuleBuilder = "Module argument must be a ModuleBuilder.";
+	public const string NotSupported_NativeCallableTarget = "Methods with NativeCallableAttribute cannot be used as delegate target.";
+	public const string NotSupported_NoCodepageData = "No data is available for encoding {0}. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method.";
+	public const string NotSupported_NonBlittableTypes = "Non-blittable parameter types are not supported for NativeCallable methods.";
+	public const string NotSupported_NonReflectedType = "Not supported in a non-reflected type.";
+	public const string NotSupported_NonStaticMethod = "Non-static methods with NativeCallableAttribute are not supported.";
+	public const string NotSupported_NoParentDefaultConstructor = "Parent does not have a default constructor. The default constructor must be explicitly defined.";
+	public const string NotSupported_NoTypeInfo = "Cannot resolve {0} to a TypeInfo object.";
+	public const string NotSupported_NYI = "This feature is not currently implemented.";
+	public const string NotSupported_ObsoleteResourcesFile = "Found an obsolete .resources file in assembly '{0}'. Rebuild that .resources file then rebuild that assembly.";
+	public const string NotSupported_OleAutBadVarType = "The given Variant type is not supported by this OleAut function.";
+	public const string NotSupported_OpenType = "Cannot create arrays of open type.";
+	public const string NotSupported_OutputStreamUsingTypeBuilder = "Output streams do not support TypeBuilders.";
+	public const string NotSupported_PIAInAppxProcess = "A Primary Interop Assembly is not supported in AppX.";
+	public const string NotSupported_Reading = "Accessor does not support reading.";
+	public const string NotSupported_ReadOnlyCollection = "Collection is read-only.";
+	public const string NotSupported_ResourceObjectSerialization = "Cannot read resources that depend on serialization.";
+	public const string NotSupported_SignalAndWaitSTAThread = "SignalAndWait on a STA thread is not supported.";
+	public const string NotSupported_StringComparison = "The string comparison type passed in is currently not supported.";
+	public const string NotSupported_SubclassOverride = "Derived classes must provide an implementation.";
+	public const string NotSupported_SymbolMethod = "Not supported in an array method of a type definition that is not complete.";
+	public const string NotSupported_TooManyArgs = "Stack size too deep. Possibly too many arguments.";
+	public const string NotSupported_Type = "Type is not supported.";
+	public const string NotSupported_TypeCannotDeserialized = "Direct deserialization of type '{0}' is not supported.";
+	public const string NotSupported_TypeNotYetCreated = "The invoked member is not supported before the type is created.";
+	public const string NotSupported_UmsSafeBuffer = "This operation is not supported for an UnmanagedMemoryStream created from a SafeBuffer.";
+	public const string NotSupported_UnitySerHolder = "The UnitySerializationHolder object is designed to transmit information about other types and is not serializable itself.";
+	public const string NotSupported_UnknownTypeCode = "TypeCode '{0}' was not valid.";
+	public const string NotSupported_WaitAllSTAThread = "WaitAll for multiple handles on a STA thread is not supported.";
+	public const string NotSupported_UnreadableStream = "Stream does not support reading.";
+	public const string NotSupported_UnseekableStream = "Stream does not support seeking.";
+	public const string NotSupported_UnwritableStream = "Stream does not support writing.";
+	public const string NotSupported_ValueClassCM = "Custom marshalers for value types are not currently supported.";
+	public const string NotSupported_ValueCollectionSet = "Mutating a value collection derived from a dictionary is not allowed.";
+	public const string NotSupported_VoidArray = "Arrays of System.Void are not supported.";
+	public const string NotSupported_WinRT_PartialTrust = "Windows Runtime is not supported in partial trust.";
+	public const string NotSupported_Writing = "Accessor does not support writing.";
+	public const string NotSupported_WrongResourceReader_Type = "This .resources file should not be read with this reader. The resource reader type is \"{0}\".";
+	public const string NullReference_This = "The pointer for this method was null.";
+	public const string ObjectDisposed_FileClosed = "Cannot access a closed file.";
+	public const string ObjectDisposed_Generic = "Cannot access a disposed object.";
+	public const string ObjectDisposed_ObjectName_Name = "Object name: '{0}'.";
+	public const string ObjectDisposed_WriterClosed = "Cannot write to a closed TextWriter.";
+	public const string ObjectDisposed_ReaderClosed = "Cannot read from a closed TextReader.";
+	public const string ObjectDisposed_ResourceSet = "Cannot access a closed resource set.";
+	public const string ObjectDisposed_StreamClosed = "Cannot access a closed Stream.";
+	public const string ObjectDisposed_ViewAccessorClosed = "Cannot access a closed accessor.";
+	public const string OperationCanceled = "The operation was canceled.";
+	public const string OutOfMemory_GCHandleMDA = "The GCHandle MDA has run out of available cookies.";
+	public const string Overflow_Byte = "Value was either too large or too small for an unsigned byte.";
+	public const string Overflow_Char = "Value was either too large or too small for a character.";
+	public const string Overflow_Currency = "Value was either too large or too small for a Currency.";
+	public const string Overflow_Decimal = "Value was either too large or too small for a Decimal.";
+	public const string Overflow_Duration = "The duration cannot be returned for TimeSpan.MinValue because the absolute value of TimeSpan.MinValue exceeds the value of TimeSpan.MaxValue.";
+	public const string Overflow_Int16 = "Value was either too large or too small for an Int16.";
+	public const string Overflow_Int32 = "Value was either too large or too small for an Int32.";
+	public const string Overflow_Int64 = "Value was either too large or too small for an Int64.";
+	public const string Overflow_NegateTwosCompNum = "Negating the minimum value of a twos complement number is invalid.";
+	public const string Overflow_NegativeUnsigned = "The string was being parsed as an unsigned number and could not have a negative sign.";
+	public const string Overflow_SByte = "Value was either too large or too small for a signed byte.";
+	public const string Overflow_TimeSpanElementTooLarge = "The TimeSpan string '{0}' could not be parsed because at least one of the numeric components is out of range or contains too many digits.";
+	public const string Overflow_TimeSpanTooLong = "TimeSpan overflowed because the duration is too long.";
+	public const string Overflow_UInt16 = "Value was either too large or too small for a UInt16.";
+	public const string Overflow_UInt32 = "Value was either too large or too small for a UInt32.";
+	public const string Overflow_UInt64 = "Value was either too large or too small for a UInt64.";
+	public const string PlatformNotSupported_ArgIterator = "ArgIterator is not supported on this platform.";
+	public const string PlatformNotSupported_ComInterop = "COM Interop is not supported on this platform.";
+	public const string PlatformNotSupported_NamedSynchronizationPrimitives = "The named version of this synchronization primitive is not supported on this platform.";
+	public const string PlatformNotSupported_NamedSyncObjectWaitAnyWaitAll = "Wait operations on multiple wait handles including a named synchronization primitive are not supported on this platform.";
+	public const string PlatformNotSupported_OSXFileLocking = "Locking/unlocking file regions is not supported on this platform. Use FileShare on the entire file instead.";
+	public const string PlatformNotSupported_ReflectionOnly = "ReflectionOnly loading is not supported on this platform.";
+	public const string PlatformNotSupported_Remoting = "Remoting is not supported on this platform.";
+	public const string PlatformNotSupported_SecureBinarySerialization = "Secure binary serialization is not supported on this platform.";
+	public const string PlatformNotSupported_StrongNameSigning = "Strong-name signing is not supported on this platform.";
+	public const string PlatformNotSupported_WinRT = "Windows Runtime is not supported on this operating system.";
+	public const string PlatformNotSupported_OverlappedIO = "This API is specific to the way in which Windows handles asynchronous I/O, and is not supported on this platform.";
+	public const string PlatformNotSupported_ITypeInfo = "Marshalling a System.Type to an unmanaged ITypeInfo or marshalling an ITypeInfo to a System.Type is not supported on this platform.";
+	public const string PlatformNotSupported_IExpando = "Marshalling an IDispatchEx to an IReflect or IExpando is not supported on this platform.";
+	public const string Policy_CannotLoadSemiTrustAssembliesDuringInit = "All assemblies loaded as part of AppDomain initialization must be fully trusted.";
+	public const string PostconditionFailed = "Postcondition failed.";
+	public const string PostconditionFailed_Cnd = "Postcondition failed: {0}";
+	public const string PostconditionOnExceptionFailed = "Postcondition failed after throwing an exception.";
+	public const string PostconditionOnExceptionFailed_Cnd = "Postcondition failed after throwing an exception: {0}";
+	public const string PreconditionFailed = "Precondition failed.";
+	public const string PreconditionFailed_Cnd = "Precondition failed: {0}";
+	public const string Rank_MultiDimNotSupported = "Only single dimension arrays are supported here.";
+	public const string Rank_MustMatch = "The specified arrays must have the same number of dimensions.";
+	public const string ReflectionTypeLoad_LoadFailed = "Unable to load one or more of the requested types.";
+	public const string ResourceReaderIsClosed = "ResourceReader is closed.";
+	public const string Resources_StreamNotValid = "Stream is not a valid resource file.";
+	public const string RFLCT_AmbigCust = "Multiple custom attributes of the same type found.";
+	public const string RFLCT_Ambiguous = "Ambiguous match found.";
+	public const string InvalidFilterCriteriaException_CritInt = "An Int32 must be provided for the filter criteria.";
+	public const string InvalidFilterCriteriaException_CritString = "A String must be provided for the filter criteria.";
+	public const string RFLCT_InvalidFieldFail = "'{0}' field specified was not found.";
+	public const string RFLCT_InvalidPropFail = "'{0}' property specified was not found.";
+	public const string RFLCT_Targ_ITargMismatch = "Object does not match target type.";
+	public const string RFLCT_Targ_StatFldReqTarg = "Non-static field requires a target.";
+	public const string RFLCT_Targ_StatMethReqTarg = "Non-static method requires a target.";
+	public const string RuntimeWrappedException = "An object that does not derive from System.Exception has been wrapped in a RuntimeWrappedException.";
+	public const string Security_CannotReadFileData = "The time zone ID '{0}' was found on the local computer, but the application does not have permission to read the file.";
+	public const string Security_CannotReadRegistryData = "The time zone ID '{0}' was found on the local computer, but the application does not have permission to read the registry information.";
+	public const string Security_RegistryPermission = "Requested registry access is not allowed.";
+	public const string SemaphoreSlim_ctor_InitialCountWrong = "The initialCount argument must be non-negative and less than or equal to the maximumCount.";
+	public const string SemaphoreSlim_ctor_MaxCountWrong = "The maximumCount argument must be a positive number. If a maximum is not required, use the constructor without a maxCount parameter.";
+	public const string SemaphoreSlim_Disposed = "The semaphore has been disposed.";
+	public const string SemaphoreSlim_Release_CountWrong = "The releaseCount argument must be greater than zero.";
+	public const string SemaphoreSlim_Wait_TimeoutWrong = "The timeout must represent a value between -1 and Int32.MaxValue, inclusive.";
+	public const string Serialization_BadParameterInfo = "Non existent ParameterInfo. Position bigger than member's parameters length.";
+	public const string Serialization_CorruptField = "The value of the field '{0}' is invalid.  The serialized data is corrupt.";
+	public const string Serialization_DateTimeTicksOutOfRange = "Invalid serialized DateTime data. Ticks must be between DateTime.MinValue.Ticks and DateTime.MaxValue.Ticks.";
+	public const string Serialization_DelegatesNotSupported = "Serializing delegates is not supported on this platform.";
+	public const string Serialization_InsufficientDeserializationState = "Insufficient state to deserialize the object. Missing field '{0}'. More information is needed.";
+	public const string Serialization_InsufficientState = "Insufficient state to return the real object.";
+	public const string Serialization_InvalidData = "An error occurred while deserializing the object.  The serialized data is corrupt.";
+	public const string Serialization_InvalidDelegateType = "Cannot serialize delegates over unmanaged function pointers, dynamic methods or methods outside the delegate creator's assembly.";
+	public const string Serialization_InvalidEscapeSequence = "The serialized data contained an invalid escape sequence '\\\\{0}'.";
+	public const string Serialization_InvalidFieldState = "Object fields may not be properly initialized.";
+	public const string Serialization_InvalidOnDeser = "OnDeserialization method was called while the object was not being deserialized.";
+	public const string Serialization_InvalidPtrValue = "An IntPtr or UIntPtr with an eight byte value cannot be deserialized on a machine with a four byte word size.";
+	public const string Serialization_InvalidType = "Only system-provided types can be passed to the GetUninitializedObject method. '{0}' is not a valid instance of a type.";
+	public const string Serialization_KeyValueDifferentSizes = "The keys and values arrays have different sizes.";
+	public const string Serialization_MemberOutOfRange = "The deserialized value of the member \"{0}\" in the class \"{1}\" is out of range.";
+	public const string Serialization_MemberTypeNotRecognized = "Unknown member type.";
+	public const string Serialization_MissField = "Field {0} is missing.";
+	public const string Serialization_MissingDateTimeData = "Invalid serialized DateTime data. Unable to find 'ticks' or 'dateData'.";
+	public const string Serialization_MissingKeys = "The Keys for this Hashtable are missing.";
+	public const string Serialization_MissingValues = "The values for this dictionary are missing.";
+	public const string Serialization_NonSerType = "Type '{0}' in Assembly '{1}' is not marked as serializable.";
+	public const string Serialization_NoParameterInfo = "Serialized member does not have a ParameterInfo.";
+	public const string Serialization_NotFound = "Member '{0}' was not found.";
+	public const string Serialization_NullKey = "One of the serialized keys is null.";
+	public const string Serialization_NullSignature = "The method signature cannot be null.";
+	public const string Serialization_OptionalFieldVersionValue = "Version value must be positive.";
+	public const string Serialization_SameNameTwice = "Cannot add the same member twice to a SerializationInfo object.";
+	public const string Serialization_StringBuilderCapacity = "The serialized Capacity property of StringBuilder must be positive, less than or equal to MaxCapacity and greater than or equal to the String length.";
+	public const string Serialization_StringBuilderMaxCapacity = "The serialized MaxCapacity property of StringBuilder must be positive and greater than or equal to the String length.";
+	public const string Serialization_UnableToFindModule = "The given module {0} cannot be found within the assembly {1}.";
+	public const string Serialization_UnknownMember = "Cannot get the member '{0}'.";
+	public const string SpinLock_Exit_SynchronizationLockException = "The calling thread does not hold the lock.";
+	public const string SpinLock_IsHeldByCurrentThread = "Thread tracking is disabled.";
+	public const string SpinLock_TryEnter_ArgumentOutOfRange = "The timeout must be a value between -1 and Int32.MaxValue, inclusive.";
+	public const string SpinLock_TryEnter_LockRecursionException = "The calling thread already holds the lock.";
+	public const string SpinLock_TryReliableEnter_ArgumentException = "The tookLock argument must be set to false before calling this method.";
+	public const string SpinWait_SpinUntil_ArgumentNull = "The condition argument is null.";
+	public const string SpinWait_SpinUntil_TimeoutWrong = "The timeout must represent a value between -1 and Int32.MaxValue, inclusive.";
+	public const string StackTrace_InFileLineNumber = "in {0}:line {1}";
+	public const string Task_ContinueWith_ESandLR = "The specified TaskContinuationOptions combined LongRunning and ExecuteSynchronously.  Synchronous continuations should not be long running.";
+	public const string Task_ContinueWith_NotOnAnything = "The specified TaskContinuationOptions excluded all continuation kinds.";
+	public const string Task_Delay_InvalidDelay = "The value needs to translate in milliseconds to -1 (signifying an infinite timeout), 0 or a positive integer less than or equal to Int32.MaxValue.";
+	public const string Task_Delay_InvalidMillisecondsDelay = "The value needs to be either -1 (signifying an infinite timeout), 0 or a positive integer.";
+	public const string Task_Dispose_NotCompleted = "A task may only be disposed if it is in a completion state (RanToCompletion, Faulted or Canceled).";
+	public const string Task_FromAsync_LongRunning = "It is invalid to specify TaskCreationOptions.LongRunning in calls to FromAsync.";
+	public const string Task_FromAsync_PreferFairness = "It is invalid to specify TaskCreationOptions.PreferFairness in calls to FromAsync.";
+	public const string Task_MultiTaskContinuation_EmptyTaskList = "The tasks argument contains no tasks.";
+	public const string Task_MultiTaskContinuation_FireOptions = "It is invalid to exclude specific continuation kinds for continuations off of multiple tasks.";
+	public const string Task_MultiTaskContinuation_NullTask = "The tasks argument included a null value.";
+	public const string Task_RunSynchronously_AlreadyStarted = "RunSynchronously may not be called on a task that was already started.";
+	public const string Task_RunSynchronously_Continuation = "RunSynchronously may not be called on a continuation task.";
+	public const string Task_RunSynchronously_Promise = "RunSynchronously may not be called on a task not bound to a delegate, such as the task returned from an asynchronous method.";
+	public const string Task_RunSynchronously_TaskCompleted = "RunSynchronously may not be called on a task that has already completed.";
+	public const string Task_Start_AlreadyStarted = "Start may not be called on a task that was already started.";
+	public const string Task_Start_ContinuationTask = "Start may not be called on a continuation task.";
+	public const string Task_Start_Promise = "Start may not be called on a promise-style task.";
+	public const string Task_Start_TaskCompleted = "Start may not be called on a task that has completed.";
+	public const string Task_ThrowIfDisposed = "The task has been disposed.";
+	public const string Task_WaitMulti_NullTask = "The tasks array included at least one null element.";
+	public const string TaskCanceledException_ctor_DefaultMessage = "A task was canceled.";
+	public const string TaskCompletionSourceT_TrySetException_NoExceptions = "The exceptions collection was empty.";
+	public const string TaskCompletionSourceT_TrySetException_NullException = "The exceptions collection included at least one null element.";
+	public const string TaskExceptionHolder_UnhandledException = "A Task's exception(s) were not observed either by Waiting on the Task or accessing its Exception property. As a result, the unobserved exception was rethrown by the finalizer thread.";
+	public const string TaskExceptionHolder_UnknownExceptionType = "(Internal)Expected an Exception or an IEnumerable<Exception>";
+	public const string TaskScheduler_ExecuteTask_WrongTaskScheduler = "ExecuteTask may not be called for a task which was previously queued to a different TaskScheduler.";
+	public const string TaskScheduler_FromCurrentSynchronizationContext_NoCurrent = "The current SynchronizationContext may not be used as a TaskScheduler.";
+	public const string TaskScheduler_InconsistentStateAfterTryExecuteTaskInline = "The TryExecuteTaskInline call to the underlying scheduler succeeded, but the task body was not invoked.";
+	public const string TaskSchedulerException_ctor_DefaultMessage = "An exception was thrown by a TaskScheduler.";
+	public const string TaskT_DebuggerNoResult = "{Not yet computed}";
+	public const string TaskT_TransitionToFinal_AlreadyCompleted = "An attempt was made to transition a task to a final state when it had already completed.";
+	public const string Threading_AbandonedMutexException = "The wait completed due to an abandoned mutex.";
+	public const string Threading_WaitHandleCannotBeOpenedException = "No handle of the given name exists.";
+	public const string Threading_WaitHandleCannotBeOpenedException_InvalidHandle = "A WaitHandle with system-wide name '{0}' cannot be created. A WaitHandle of a different type might have the same name.";
+	public const string Threading_WaitHandleTooManyPosts = "The WaitHandle cannot be signaled because it would exceed its maximum count.";
+	public const string Threading_SemaphoreFullException = "Adding the specified count to the semaphore would cause it to exceed its maximum count.";
+	public const string Threading_ThreadInterrupted = "Thread was interrupted from a waiting state.";
+	public const string ThreadLocal_Disposed = "The ThreadLocal object has been disposed.";
+	public const string ThreadLocal_Value_RecursiveCallsToValue = "ValueFactory attempted to access the Value property of this instance.";
+	public const string ThreadLocal_ValuesNotAvailable = "The ThreadLocal object is not tracking values. To use the Values property, use a ThreadLocal constructor that accepts the trackAllValues parameter and set the parameter to true.";
+	public const string TimeZoneNotFound_MissingData = "The time zone ID '{0}' was not found on the local computer.";
+	public const string TypeInitialization_Default = "Type constructor threw an exception.";
+	public const string TypeInitialization_Type = "The type initializer for '{0}' threw an exception.";
+	public const string TypeLoad_ResolveNestedType = "Could not resolve nested type '{0}' in type \"{1}'.";
+	public const string TypeLoad_ResolveType = "Could not resolve type '{0}'.";
+	public const string TypeLoad_ResolveTypeFromAssembly = "Could not resolve type '{0}' in assembly '{1}'.";
+	public const string UnauthorizedAccess_IODenied_NoPathName = "Access to the path is denied.";
+	public const string UnauthorizedAccess_IODenied_Path = "Access to the path '{0}' is denied.";
+	public const string UnauthorizedAccess_MemStreamBuffer = "MemoryStream's internal buffer cannot be accessed.";
+	public const string UnauthorizedAccess_RegistryKeyGeneric_Key = "Access to the registry key '{0}' is denied.";
+	public const string UnknownError_Num = "Unknown error \"{0}\".";
+	public const string Verification_Exception = "Operation could destabilize the runtime.";
+	public const string Word_At = "at";
+	public const string DebugAssertBanner = "---- DEBUG ASSERTION FAILED ----";
+	public const string DebugAssertLongMessage = "---- Assert Long Message ----";
+	public const string DebugAssertShortMessage = "---- Assert Short Message ----";
+	public const string LockRecursionException_ReadAfterWriteNotAllowed = "A read lock may not be acquired with the write lock held in this mode.";
+	public const string LockRecursionException_RecursiveReadNotAllowed = "Recursive read lock acquisitions not allowed in this mode.";
+	public const string LockRecursionException_RecursiveWriteNotAllowed = "Recursive write lock acquisitions not allowed in this mode.";
+	public const string LockRecursionException_RecursiveUpgradeNotAllowed = "Recursive upgradeable lock acquisitions not allowed in this mode.";
+	public const string LockRecursionException_WriteAfterReadNotAllowed = "Write lock may not be acquired with read lock held. This pattern is prone to deadlocks. Please ensure that read locks are released before taking a write lock. If an upgrade is necessary, use an upgrade lock in place of the read lock.";
+	public const string SynchronizationLockException_MisMatchedUpgrade = "The upgradeable lock is being released without being held.";
+	public const string SynchronizationLockException_MisMatchedRead = "The read lock is being released without being held.";
+	public const string SynchronizationLockException_IncorrectDispose = "The lock is being disposed while still being used. It either is being held by a thread and/or has active waiters waiting to acquire the lock.";
+	public const string LockRecursionException_UpgradeAfterReadNotAllowed = "Upgradeable lock may not be acquired with read lock held.";
+	public const string LockRecursionException_UpgradeAfterWriteNotAllowed = "Upgradeable lock may not be acquired with write lock held in this mode. Acquiring Upgradeable lock gives the ability to read along with an option to upgrade to a writer.";
+	public const string SynchronizationLockException_MisMatchedWrite = "The write lock is being released without being held.";
+	public const string ConcurrentStack_PushPopRange_CountOutOfRange = "The count argument must be greater than or equal to zero.";
+	public const string ConcurrentStack_PushPopRange_InvalidCount = "The sum of the startIndex and count arguments must be less than or equal to the collection's Count.";
+	public const string ConcurrentStack_PushPopRange_StartOutOfRange = "The startIndex argument must be greater than or equal to zero.";
+	public const string NotSupported_SignatureType = "This method is not supported on signature types.";
+	public const string MemoryDisposed = "Memory<T> has been disposed.";
+	public const string Memory_OutstandingReferences = "Release all references before disposing this instance.";
+	public const string HashCode_HashCodeNotSupported = "HashCode is a mutable struct and should not be compared with other HashCodes. Use ToHashCode to retrieve the computed hash code.";
+	public const string HashCode_EqualityNotSupported = "HashCode is a mutable struct and should not be compared with other HashCodes.";
+	public const string Arg_TypeNotSupported = "Specified type is not supported";
+	public const string IO_InvalidReadLength = "The read operation returned an invalid length.";
+	public const string Arg_BasePathNotFullyQualified = "Basepath argument is not fully qualified.";
+	public const string Arg_ElementsInSourceIsGreaterThanDestination = "Number of elements in source vector is greater than the destination array";
+	public const string Arg_NullArgumentNullRef = "The method was called with a null array argument.";
+	public const string Argument_CannotPrepareAbstract = "Abstract methods cannot be prepared.";
+	public const string Argument_InvalidGenericInstantiation = "The given generic instantiation was invalid.";
+	public const string Argument_OverlapAlignmentMismatch = "Overlapping spans have mismatching alignment.";
+	public const string Arg_InsufficientNumberOfElements = "At least {0} element(s) are expected in the parameter \"{1}\".";
+	public const string Arg_MustBeNullTerminatedString = "The string must be null-terminated.";
+	public const string ArgumentOutOfRange_Week_ISO = "The week parameter must be in the range 1 through 53.";
+	public const string Argument_BadPInvokeMethod = "PInvoke methods must be static and native and cannot be abstract.";
+	public const string Argument_BadPInvokeOnInterface = "PInvoke methods cannot exist on interfaces.";
+	public const string Argument_MethodRedefined = "Method has been already defined.";
+	public const string Argument_CannotExtractScalar = "Cannot extract a Unicode scalar value from the specified index in the input.";
+	public const string Argument_CannotParsePrecision = "Characters following the format symbol must be a number of {0} or less.";
+	public const string Argument_GWithPrecisionNotSupported = "The 'G' format combined with a precision is not supported.";
+	public const string Argument_PrecisionTooLarge = "Precision cannot be larger than {0}.";
+	public const string Arg_EnumNotCloneable = "The supplied object does not implement ICloneable.";
+	public const string InvalidOp_InvalidNewEnumVariant = "The returned enumerator does not implement IEnumVARIANT.";
+	public const string IndexOutOfRange_ArrayWithOffset = "";
+	public const string Argument_NotIsomorphic = "";
+	public const string Argument_StructArrayTooLarge = "";
+}

+ 96 - 0
mcs/class/System.Private.CoreLib/Stubs.cs

@@ -0,0 +1,96 @@
+using System.Reflection;
+using System.Collections.Generic;
+
+namespace System
+{
+	public abstract class RuntimeType : TypeInfo
+	{
+		internal Object GenericCache;
+	}
+
+	static class MonoCustomAttrs
+	{
+		internal static object[] GetCustomAttributes (ICustomAttributeProvider obj, Type attributeType, bool inherit) => throw new NotImplementedException ();
+
+		internal static bool IsDefined (ICustomAttributeProvider obj, Type attributeType, bool inherit) => throw new NotImplementedException ();
+
+		internal static IList<CustomAttributeData> GetCustomAttributesData (ICustomAttributeProvider obj, Type attributeType, bool inherit) => throw new NotImplementedException ();
+
+		internal static IList<CustomAttributeData> GetCustomAttributesData (ICustomAttributeProvider obj, bool inherit = false) => throw new NotImplementedException ();
+	}
+}
+
+namespace System.Threading
+{
+	public sealed class Timer : System.MarshalByRefObject, System.IDisposable
+	{
+		public Timer(System.Threading.TimerCallback callback) { }
+		public Timer(System.Threading.TimerCallback callback, object state, int dueTime, int period) { }
+		public Timer(System.Threading.TimerCallback callback, object state, long dueTime, long period) { }
+		public Timer(System.Threading.TimerCallback callback, object state, System.TimeSpan dueTime, System.TimeSpan period) { }
+		[System.CLSCompliantAttribute(false)]
+		public Timer(System.Threading.TimerCallback callback, object state, uint dueTime, uint period) { }
+		public bool Change(int dueTime, int period) { throw null; }
+		public bool Change(long dueTime, long period) { throw null; }
+		public bool Change(System.TimeSpan dueTime, System.TimeSpan period) { throw null; }
+		[System.CLSCompliantAttribute(false)]
+		public bool Change(uint dueTime, uint period) { throw null; }
+		public void Dispose() { }
+		public bool Dispose(System.Threading.WaitHandle notifyObject) { throw null; }
+		public System.Threading.Tasks.ValueTask DisposeAsync() { throw null; }
+	}
+
+	internal class TimerQueueTimer
+	{
+		public TimerQueueTimer (TimerCallback timerCallback, object state, uint dueTime, uint period, bool flowExecutionContext)
+		{
+		}
+
+		internal bool Change(uint dueTime, uint period)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public void Close ()
+		{
+		}
+	}
+}
+
+namespace System.Reflection
+{
+	abstract class MonoField : RuntimeFieldInfo
+	{
+		internal object UnsafeGetValue (object obj) => throw new NotImplementedException ();
+	}
+
+	abstract class MonoMethod : MethodInfo
+	{
+		internal MethodInfo GetBaseMethod () => throw new NotImplementedException ();
+	}
+
+	abstract class RuntimeModule
+	{
+	}
+
+	abstract class RuntimeFieldInfo : FieldInfo
+	{
+		internal RuntimeType GetDeclaringTypeInternal () => throw new NotImplementedException ();
+	}
+
+	public partial class CustomAttributeData
+	{
+		protected CustomAttributeData() { }
+		public virtual System.Type AttributeType { get { throw null; } }
+		public virtual System.Reflection.ConstructorInfo Constructor { get { throw null; } }
+		public virtual System.Collections.Generic.IList<System.Reflection.CustomAttributeTypedArgument> ConstructorArguments { get { throw null; } }
+		public virtual System.Collections.Generic.IList<System.Reflection.CustomAttributeNamedArgument> NamedArguments { get { throw null; } }
+		public override bool Equals(object obj) { throw null; }
+		public static System.Collections.Generic.IList<System.Reflection.CustomAttributeData> GetCustomAttributes(System.Reflection.Assembly target) { throw null; }
+		public static System.Collections.Generic.IList<System.Reflection.CustomAttributeData> GetCustomAttributes(System.Reflection.MemberInfo target) { throw null; }
+		public static System.Collections.Generic.IList<System.Reflection.CustomAttributeData> GetCustomAttributes(System.Reflection.Module target) { throw null; }
+		public static System.Collections.Generic.IList<System.Reflection.CustomAttributeData> GetCustomAttributes(System.Reflection.ParameterInfo target) { throw null; }
+		public override int GetHashCode() { throw null; }
+		public override string ToString() { throw null; }
+	}
+}

+ 19 - 0
mcs/class/System.Private.CoreLib/System.Collections.Generic/Comparer.cs

@@ -0,0 +1,19 @@
+namespace System.Collections.Generic
+{
+	partial class Comparer<T>
+	{
+		public static Comparer<T> Default {
+			get {
+				throw new NotImplementedException();
+			}
+		}
+	}
+
+	partial class EnumComparer<T>
+	{
+		public override int Compare(T x, T y)
+		{
+			throw new NotImplementedException();
+		}
+	}
+}

+ 19 - 0
mcs/class/System.Private.CoreLib/System.Collections.Generic/EqualityComparer.cs

@@ -0,0 +1,19 @@
+namespace System.Collections.Generic
+{
+	partial class EqualityComparer<T>
+	{
+		public static EqualityComparer<T> Default {
+			get {
+				throw new NotImplementedException ();
+			}
+		}
+	}
+
+	partial class EnumEqualityComparer<T>
+	{
+		public override bool Equals(T x, T y)
+		{
+			throw new NotImplementedException ();
+		}
+	}
+}

+ 15 - 0
mcs/class/System.Private.CoreLib/System.Diagnostics.Contracts/Contract.cs

@@ -0,0 +1,15 @@
+namespace System.Diagnostics.Contracts
+{
+	partial class Contract
+	{
+		/* Requires ContractsBCL change to land
+		static void AssertMustUseRewriter (ContractFailureKind kind, string contractKind)
+		{
+		}
+
+		static void ReportFailure (ContractFailureKind failureKind, string userMessage, string conditionText, Exception innerException)
+		{
+		}
+		*/
+	}
+}

+ 40 - 0
mcs/class/System.Private.CoreLib/System.Diagnostics.Tracing/EventSource.cs

@@ -0,0 +1,40 @@
+namespace System.Diagnostics.Tracing
+{
+	partial class EventSource
+	{
+		private static readonly bool m_EventSourcePreventRecursion = false;
+
+		public static void SetCurrentThreadActivityId (Guid activityId)
+		{
+		}
+
+		public static void SetCurrentThreadActivityId (Guid activityId, out Guid oldActivityThatWillContinue)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public static Guid CurrentThreadActivityId {
+			get {
+				throw new NotImplementedException ();
+			}
+		}
+
+		private int GetParameterCount (EventMetadata eventData)
+		{
+			return 0;
+		}
+
+		private Type GetDataType (EventMetadata eventData, int parameterId)
+		{
+			return null;
+		}
+	}
+
+	internal partial class ManifestBuilder
+	{
+		private string GetTypeNameHelper (Type type)
+		{
+			throw new NotImplementedException ();
+		}
+	}
+}

+ 15 - 0
mcs/class/System.Private.CoreLib/System.Diagnostics/Debugger.cs

@@ -0,0 +1,15 @@
+using System.Runtime.CompilerServices;
+
+namespace System.Diagnostics
+{
+	public static class Debugger
+	{
+		public static readonly string DefaultCategory;
+		public static bool IsAttached { get { throw null; } }
+		public static void Break() { }
+		public static bool IsLogging() { throw null; }
+		public static bool Launch() { throw null; }
+		public static void Log(int level, string category, string message) {}
+		public static void NotifyOfCrossThreadDependency() { }
+	}
+}

+ 14 - 0
mcs/class/System.Private.CoreLib/System.Diagnostics/StackFrame.cs

@@ -0,0 +1,14 @@
+using System.Text;
+
+namespace System.Diagnostics
+{
+	partial class StackFrame
+	{
+		void BuildStackFrame (int skipFrames, bool needFileInfo)
+		{
+
+		}
+
+		bool AppendStackFrameWithoutMethodBase (StringBuilder sb) => false;
+	}
+}

+ 20 - 0
mcs/class/System.Private.CoreLib/System.Diagnostics/StackTrace.cs

@@ -0,0 +1,20 @@
+namespace System.Diagnostics
+{
+	partial class StackTrace
+	{
+		internal StackTrace (StackFrame[] frames)
+		{
+			throw new NotImplementedException ();
+		}
+
+		void InitializeForCurrentThread (int skipFrames, bool fNeedFileInfo)
+		{
+
+		}
+		
+		void InitializeForException (Exception e, int skipFrames, bool fNeedFileInfo)
+		{
+
+		}
+	}
+}

+ 11 - 0
mcs/class/System.Private.CoreLib/System.Globalization/CultureData.cs

@@ -0,0 +1,11 @@
+namespace System.Globalization
+{
+	partial class CultureData
+	{
+		public static CultureData GetCultureData (string cultureName, bool useUserOverride, int datetimeIndex, int calendarId, int numberIndex, string iso2lang,
+			int ansiCodePage, int oemCodePage, int macCodePage, int ebcdicCodePage, bool rightToLeft, string listSeparator)
+		{
+			return null;
+		}
+	}
+}

+ 17 - 0
mcs/class/System.Private.CoreLib/System.Globalization/CultureInfo.cs

@@ -0,0 +1,17 @@
+namespace System.Globalization
+{
+	partial class CultureInfo
+	{
+#region referencesources legacy
+		internal static CultureInfo ConstructCurrentCulture () => throw new NotImplementedException ();
+
+		internal static CultureInfo ConstructCurrentUICulture () => throw new NotImplementedException ();
+
+		internal static CultureInfo UserDefaultCulture {
+			get {
+				throw new NotImplementedException ();
+			}
+		}
+#endregion
+	}
+}

+ 11 - 0
mcs/class/System.Private.CoreLib/System.Globalization/GlobalizationMode.cs

@@ -0,0 +1,11 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+namespace System.Globalization
+{
+    internal static partial class GlobalizationMode
+    {
+        internal static bool Invariant => false;
+    }
+}

+ 10 - 0
mcs/class/System.Private.CoreLib/System.IO/FileLoadException.cs

@@ -0,0 +1,10 @@
+namespace System.IO
+{
+	partial class FileLoadException
+	{
+		internal static string FormatFileLoadExceptionMessage (string fileName, int hResult)
+		{
+			return "";
+		}
+	}
+}

+ 15 - 0
mcs/class/System.Private.CoreLib/System.IO/Stream.cs

@@ -0,0 +1,15 @@
+namespace System.IO
+{
+	partial class Stream
+	{
+		private bool HasOverriddenBeginEndRead ()
+		{
+			throw new NotImplementedException ();
+		}
+
+		private bool HasOverriddenBeginEndWrite ()
+		{
+			throw new NotImplementedException ();
+		}
+	}
+}

+ 264 - 0
mcs/class/System.Private.CoreLib/System.Private.CoreLib.csproj

@@ -0,0 +1,264 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <!-- Include common build properties -->
+<!--  <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.props))\dir.props" /> -->
+  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
+  <!-- Compilation options -->
+  <PropertyGroup>
+    <AvailablePlatforms>x64,x86,arm,armel,arm64</AvailablePlatforms>
+    <Configuration Condition=" '$(Configuration)' == '' ">$(BuildType)</Configuration>
+    <Platform Condition=" '$(Platform)' == '' ">$(BuildArch)</Platform>
+    <Platform Condition=" '$(Platform)' == 'armel' ">arm</Platform>
+    <ProjectGuid>{DD18B4BA-3B49-437B-9E34-41EF8A640CE0}</ProjectGuid>
+    <OutputType>Library</OutputType>
+    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
+    <!-- This prevents the default MsBuild targets from referencing System.Core.dll -->
+    <AddAdditionalExplicitAssemblyReferences>false</AddAdditionalExplicitAssemblyReferences>
+    <!-- These prevent the default MsBuild targets from referencing System.dll and mscorlib.dll -->
+    <ExcludeMscorlibFacade>true</ExcludeMscorlibFacade>
+    <NoStdLib>true</NoStdLib>
+    <NoCompilerStandardLib>true</NoCompilerStandardLib>
+    <SubsystemVersion>6.00</SubsystemVersion>
+    <UTF8OutPut>true</UTF8OutPut>
+    <HighEntropyVA>true</HighEntropyVA>
+    <ErrorReport>prompt</ErrorReport>
+    <CLSCompliant>true</CLSCompliant>
+    <WarningLevel>4</WarningLevel>
+    <TreatWarningsAsErrors>false</TreatWarningsAsErrors>
+    <WarningsNotAsErrors>$(WarningsNotAsErrors);618</WarningsNotAsErrors>
+    <NoWarn>649,3019,414,169,3015,591,1573,1591,0419</NoWarn>
+    <GenerateTargetFrameworkAttribute>false</GenerateTargetFrameworkAttribute>
+    <SignAssembly>true</SignAssembly>
+    <DelaySign>true</DelaySign>
+    <DefineConstants>$(DefineConstants);_USE_NLS_PLUS_TABLE;CODE_ANALYSIS_BASELINE;netcoreapp</DefineConstants>
+    <!-- We don't use any of MSBuild's resolution logic for resolving the framework, so just set these two properties to any folder that exists to skip
+         the GenerateReferenceAssemblyPaths task (not target) and to prevent it from outputting a warning (MSB3644). -->
+    <_TargetFrameworkDirectories>$(MSBuildThisFileDirectory)/Documentation</_TargetFrameworkDirectories>
+    <_FullFrameworkReferenceAssemblyPaths>$(MSBuildThisFileDirectory)/Documentation</_FullFrameworkReferenceAssemblyPaths>
+    <SkipCommonResourcesIncludes>true</SkipCommonResourcesIncludes>
+    <LangVersion>latest</LangVersion>
+<!--
+    <DocumentationFile>$(OutputPath)$(MSBuildProjectName).xml</DocumentationFile>
+-->
+  </PropertyGroup>
+  <!-- Platform specific properties -->
+  <PropertyGroup Condition="'$(Platform)' == 'x64'">
+    <PlatformTarget>x64</PlatformTarget>
+    <Prefer32Bit>false</Prefer32Bit>
+    <BaseAddress>0x180000000</BaseAddress>
+    <DefineConstants>BIT64;AMD64;$(DefineConstants)</DefineConstants>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Platform)' == 'x86'">
+    <PlatformTarget>x86</PlatformTarget>
+    <BaseAddress>0x10000000</BaseAddress>
+    <DefineConstants>BIT32;$(DefineConstants)</DefineConstants>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Platform)' == 'arm'">
+    <PlatformTarget>arm</PlatformTarget>
+    <DefineConstants>BIT32;ARM;$(DefineConstants)</DefineConstants>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Platform)' == 'arm64'">
+    <PlatformTarget>AnyCPU</PlatformTarget>
+    <DefineConstants>BIT64;ARM64;$(DefineConstants)</DefineConstants>
+  </PropertyGroup>
+  <!-- Configuration specific properties -->
+  <PropertyGroup Condition="'$(Configuration)' == 'Debug' or '$(Configuration)' == 'Checked'">
+    <DebugSymbols>true</DebugSymbols>
+    <Optimize Condition="'$(Optimize)' == '' and '$(Configuration)' == 'Debug'">false</Optimize>
+    <Optimize Condition="'$(Optimize)' == '' and '$(Configuration)' == 'Checked'">true</Optimize>
+    <DebugType Condition="'$(DebugType)' == ''">full</DebugType>
+    <DefineConstants>_LOGGING;DEBUG;TRACE;$(DefineConstants)</DefineConstants>
+    <DefineConstants Condition="'$(Platform)' == 'x86' or '$(Platform)' == 'x64'">CODE_ANALYSIS;$(DefineConstants)</DefineConstants>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)' == 'Release'">
+    <DebugSymbols>true</DebugSymbols>
+    <Optimize Condition="'$(Optimize)' == ''">true</Optimize>
+    <DebugType Condition="'$(DebugType)' == ''">pdbOnly</DebugType>
+    <DefineConstants>TRACE;$(DefineConstants)</DefineConstants>
+  </PropertyGroup>
+  <!-- Make portable PDBs on Unix -->
+  <PropertyGroup Condition="'$(OsEnvironment)' == 'Unix'">
+    <DebugType>portable</DebugType>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(TargetsOSX)' == 'true'">
+    <DefineConstants>PLATFORM_OSX;$(DefineConstants)</DefineConstants>
+  </PropertyGroup>
+  <!-- Assembly attributes -->
+  <PropertyGroup>
+    <AssemblyName>System.Private.CoreLib</AssemblyName>
+    <AssemblyVersion>4.0.0.0</AssemblyVersion>
+    <MajorVersion>4</MajorVersion>
+    <MinorVersion>6</MinorVersion>
+    <ExcludeAssemblyInfoPartialFile>true</ExcludeAssemblyInfoPartialFile>
+  </PropertyGroup>
+  <!--
+    Helper Paths
+  -->
+  <PropertyGroup>
+    <CommonPath>$(MSBuildThisFileDirectory)Common</CommonPath>
+    <BclSourcesRoot>$(MSBuildThisFileDirectory)src</BclSourcesRoot>
+    <MscorlibDir>$(MSBuildThisFileDirectory)</MscorlibDir>
+    <NlpObjDir>$(BclSourcesRoot)\System\Globalization\Tables</NlpObjDir>
+  </PropertyGroup>
+  <!-- Sources -->
+  <ItemGroup>
+      <Compile Include="AssemblyInfo.cs" />
+      <Compile Include="Resources\SR.cs" />
+  </ItemGroup>
+  <ItemGroup>
+      <Compile Include="Stubs.cs" />
+
+      <Compile Include="Internal.Runtime.Augments\RuntimeThread.cs" />
+      <Compile Include="Microsoft.Win32\UnsafeNativeMethods.cs" />
+      <Compile Include="Microsoft.Win32.SafeHandles\SafeWaitHandle.Unix.cs" />
+      <Compile Include="System\AppContext.cs" />
+      <Compile Include="System\Activator.cs" />
+      <Compile Include="System\Array.cs" />
+      <Compile Include="System\Attribute.cs" />
+      <Compile Include="System\DefaultBinder.cs" />
+      <Compile Include="System\DateTime.cs" />
+      <Compile Include="System\Environment.cs" />
+      <Compile Include="System\Exception.cs" />
+      <Compile Include="System\Object.cs" />
+      <Compile Include="System\Math.cs" />
+      <Compile Include="System\MathF.cs" />
+      <Compile Include="System\MissingMemberException.cs" />
+      <Compile Include="System\ModuleHandle.cs" />
+      <Compile Include="System\NotImplemented.cs" />
+      <Compile Include="System\RuntimeFieldHandle.cs" />
+      <Compile Include="System\RuntimeMethodHandle.cs" />
+      <Compile Include="System\RuntimeTypeHandle.cs" />
+      <Compile Include="System\Type.cs" />
+      <Compile Include="System.Globalization\GlobalizationMode.cs" />
+      <Compile Include="System.Globalization\CultureData.cs" />
+      <Compile Include="System.Globalization\CultureInfo.cs" />
+      <Compile Include="System.Collections.Generic\Comparer.cs" />
+      <Compile Include="System.Collections.Generic\EqualityComparer.cs" />
+      <Compile Include="System.Diagnostics\Debugger.cs" />
+      <Compile Include="System.Diagnostics\StackFrame.cs" />
+      <Compile Include="System.Diagnostics\StackTrace.cs" />
+      <Compile Include="System.Diagnostics.Contracts\Contract.cs" />
+      <Compile Include="System.Diagnostics.Tracing\EventSource.cs" />
+      <Compile Include="System.IO\Stream.cs" />
+      <Compile Include="System.IO\FileLoadException.cs" />
+      <Compile Include="System.Reflection\Assembly.cs" />
+      <Compile Include="System.Reflection\AssemblyName.cs" />
+      <Compile Include="System.Reflection\CustomAttributeExtensions.cs" />
+      <Compile Include="System.Reflection\FieldInfo.cs" />
+      <Compile Include="System.Reflection\MethodBase.cs" />
+      <Compile Include="System.Reflection.Emit\Stubs.cs" />
+      <Compile Include="System.Reflection.Metadata\AssemblyExtensions.cs" />
+      <Compile Include="System.Resources\ResourceManager.cs" />
+      <Compile Include="System.Runtime.CompilerServices\RuntimeHelpers.cs" />
+      <Compile Include="System.Runtime.CompilerServices\RuntimeFeature.cs" />
+      <Compile Include="System.Runtime.InteropServices\ComEventsHelper.cs" />
+      <Compile Include="System.Runtime.InteropServices\CriticalHandle.cs" />
+      <Compile Include="System.Runtime.InteropServices\InteropExtensions.cs" />
+      <Compile Include="System.Runtime.InteropServices\Marshal.cs" />
+      <Compile Include="System.Runtime.Loader\AssemblyLoadContext.cs" />
+      <Compile Include="System.Threading\EventWaitHandle.cs" />
+      <Compile Include="System.Threading\Interlocked.cs" />
+      <Compile Include="System.Threading\Mutex.cs" />
+      <Compile Include="System.Threading\Overlapped.cs" />
+      <Compile Include="System.Threading\PreAllocatedOverlapped.cs" />
+      <Compile Include="System.Threading\Semaphore.cs" />
+      <Compile Include="System.Threading\SynchronizationContext.cs" />
+      <Compile Include="System.Threading\Thread.cs" />
+      <Compile Include="System.Threading\ThreadPool.cs" />
+      <Compile Include="System.Threading\ThreadPoolBoundHandle.cs" />
+  </ItemGroup>
+  <ItemGroup>
+      <Compile Include="temp\*.cs" />
+  </ItemGroup>
+  <ItemGroup>
+      <Compile Include="..\..\build\common\SR.cs" />
+
+      <Compile Include="..\corlib\coreclr\Math.CoreCLR.cs" />
+      <Compile Include="..\corlib\coreclr\SorterArray.cs" />
+      <Compile Include="..\corlib\corefx\DateTime.cs" />
+      <Compile Include="..\corlib\corefx\SynchronizationContext.cs" />
+      <Compile Include="..\corlib\corefx\RuntimeImports.cs" />
+      <Compile Include="..\corlib\corert\ThreadPool.cs" />
+
+      <Compile Include="..\corlib\ReferenceSources\Array.cs" />
+      <Compile Include="..\corlib\ReferenceSources\Buffer.cs" />
+      <Compile Include="..\corlib\ReferenceSources\JitHelpers.cs" />
+      <Compile Include="..\corlib\ReferenceSources\String.cs" />
+
+      <Compile Include="..\corlib\Mono\RuntimeStructs.cs" />
+
+      <Compile Include="..\corlib\System\Array.cs" />
+      <Compile Include="..\corlib\System\ArgIterator.cs" />
+      <Compile Include="..\corlib\System\Delegate.cs" />
+      <Compile Include="..\corlib\System\DelegateSerializationHolder.cs" />
+      <Compile Include="..\corlib\System\EmptyArray.cs" />
+      <Compile Include="..\corlib\System\MathF.mono.cs" />
+      <Compile Include="..\corlib\System\MulticastDelegate.cs" />
+      <Compile Include="..\corlib\System\RuntimeArgumentHandle.cs" />
+      <Compile Include="..\corlib\System\ValueType.cs" />
+      <Compile Include="..\corlib\System\WeakReference.cs" />
+      <Compile Include="..\corlib\System\WeakReference_T.cs" />
+
+      <Compile Include="..\corlib\System.Runtime.InteropServices\SafeHandle.cs" />
+
+      <Compile Include="..\corlib\System.Runtime.CompilerServices\ConditionalWeakTable.cs" />
+      <Compile Include="..\corlib\System.Runtime.CompilerServices\PreserveDependencyAttribute.cs" />
+      <Compile Include="..\corlib\System.Runtime.CompilerServices\RuntimeHelpers.cs" />
+
+      <Compile Include="..\corlib\System.Threading\Interlocked.cs" />
+      <Compile Include="..\corlib\System.Threading\Monitor.cs" />
+      <Compile Include="..\corlib\System.Threading\NativeEventCalls.cs" />
+      <Compile Include="..\corlib\System.Threading\RegisteredWaitHandle.cs" />
+      <Compile Include="..\corlib\System.Threading\Thread.cs" />
+      <Compile Include="..\corlib\System.Threading\TimerCallback.cs" />
+      <Compile Include="..\corlib\System.Threading\Volatile.cs" />
+      <Compile Include="..\corlib\System.Threading\WaitHandle.cs" />
+
+      <Compile Include="..\corlib\System.Runtime.InteropServices\GCHandle.cs" />
+  </ItemGroup>
+  <ItemGroup>
+      <Compile Include="..\referencesource\mscorlib\system\buffer.cs" />
+      <Compile Include="..\referencesource\mscorlib\system\exception.cs" />
+      <Compile Include="..\referencesource\mscorlib\system\enum.cs" />
+      <Compile Include="..\referencesource\mscorlib\system\gc.cs" />
+      <Compile Include="..\referencesource\mscorlib\system\typeloadexception.cs" />
+      <Compile Include="..\referencesource\mscorlib\system\typedreference.cs" />
+      <Compile Include="..\referencesource\mscorlib\system\threading\monitor.cs" />
+      <Compile Include="..\referencesource\mscorlib\system\threading\thread.cs" />
+      <Compile Include="..\referencesource\mscorlib\system\threading\threadpool.cs" />
+      <Compile Include="..\referencesource\mscorlib\system\threading\waithandle.cs" />
+
+      <Compile Include="..\referencesource\mscorlib\system\runtime\interopservices\safehandle.cs" />
+  </ItemGroup>
+  <ItemGroup>
+      <Compile Include="..\..\..\external\corert\src\System.Private.CoreLib\src\System\Array.cs" />
+      <Compile Include="..\..\..\external\corert\src\System.Private.CoreLib\src\System\Collections\Generic\ArraySortHelper.CoreRT.cs" />
+      <Compile Include="..\..\..\external\corert\src\System.Private.CoreLib\src\System\Reflection\CustomAttributeNamedArgument.cs" />
+      <Compile Include="..\..\..\external\corert\src\System.Private.CoreLib\src\System\Reflection\CustomAttributeTypedArgument.cs" />
+      <Compile Include="..\..\..\external\corert\src\System.Private.CoreLib\src\System\Reflection\MissingMetadataException.cs" />
+      <Compile Include="..\corlib\corert\RuntimeAugments.cs" />
+
+      <Compile Include="..\..\..\external\corert\src\Runtime.Base\src\System\Runtime\InteropServices\GCHandleType.cs" />
+  </ItemGroup>
+
+  <!-- Mono extensions -->
+  <PropertyGroup>
+    <DefineConstants>FEATURE_DEFAULT_INTERFACES;FEATURE_MANAGED_ETW_CHANNELS;$(DefineConstants)</DefineConstants>
+
+    <DefineConstants>MONO;NETCORE;DISABLE_REMOTING;$(DefineConstants)</DefineConstants>
+    <NoWarn>3021,$(NoWarn)</NoWarn>
+  </PropertyGroup>
+
+  <Import Project="..\..\..\netcore\System.Private.CoreLib\shared\System.Private.CoreLib.Shared.projitems" />
+
+<!--  <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" /> -->
+  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+
+  <PropertyGroup>
+    <!-- Overwrite the key that we are going to use for signing -->
+    <AssemblyOriginatorKeyFile>..\silverlight.pub</AssemblyOriginatorKeyFile>
+    <!-- Don't need a strong name signature because we only ship the native image -->
+    <StrongNameSig>None</StrongNameSig>
+  </PropertyGroup>
+</Project>
+

+ 0 - 2
mcs/class/System.Private.CoreLib/System.Private.CoreLib.dll.sources

@@ -1,2 +0,0 @@
-AssemblyInfo.cs
-../corlib/System/Object.cs

+ 558 - 0
mcs/class/System.Private.CoreLib/System.Reflection.Emit/Stubs.cs

@@ -0,0 +1,558 @@
+namespace System.Reflection.Emit
+{
+	public partial class CustomAttributeBuilder
+	{
+		public CustomAttributeBuilder(System.Reflection.ConstructorInfo con, object[] constructorArgs) { }
+		public CustomAttributeBuilder(System.Reflection.ConstructorInfo con, object[] constructorArgs, System.Reflection.FieldInfo[] namedFields, object[] fieldValues) { }
+		public CustomAttributeBuilder(System.Reflection.ConstructorInfo con, object[] constructorArgs, System.Reflection.PropertyInfo[] namedProperties, object[] propertyValues) { }
+		public CustomAttributeBuilder(System.Reflection.ConstructorInfo con, object[] constructorArgs, System.Reflection.PropertyInfo[] namedProperties, object[] propertyValues, System.Reflection.FieldInfo[] namedFields, object[] fieldValues) { }
+	}
+	public partial class ILGenerator
+	{
+		internal ILGenerator() { }
+		public virtual int ILOffset { get { throw null; } }
+		public virtual void BeginCatchBlock(System.Type exceptionType) { }
+		public virtual void BeginExceptFilterBlock() { }
+		public virtual System.Reflection.Emit.Label BeginExceptionBlock() { throw null; }
+		public virtual void BeginFaultBlock() { }
+		public virtual void BeginFinallyBlock() { }
+		public virtual void BeginScope() { }
+		public virtual System.Reflection.Emit.LocalBuilder DeclareLocal(System.Type localType) { throw null; }
+		public virtual System.Reflection.Emit.LocalBuilder DeclareLocal(System.Type localType, bool pinned) { throw null; }
+		public virtual System.Reflection.Emit.Label DefineLabel() { throw null; }
+		public virtual void Emit(System.Reflection.Emit.OpCode opcode) { }
+		public virtual void Emit(System.Reflection.Emit.OpCode opcode, byte arg) { }
+		public virtual void Emit(System.Reflection.Emit.OpCode opcode, double arg) { }
+		public virtual void Emit(System.Reflection.Emit.OpCode opcode, short arg) { }
+		public virtual void Emit(System.Reflection.Emit.OpCode opcode, int arg) { }
+		public virtual void Emit(System.Reflection.Emit.OpCode opcode, long arg) { }
+		public virtual void Emit(System.Reflection.Emit.OpCode opcode, System.Reflection.ConstructorInfo con) { }
+		public virtual void Emit(System.Reflection.Emit.OpCode opcode, System.Reflection.Emit.Label label) { }
+		public virtual void Emit(System.Reflection.Emit.OpCode opcode, System.Reflection.Emit.Label[] labels) { }
+		public virtual void Emit(System.Reflection.Emit.OpCode opcode, System.Reflection.Emit.LocalBuilder local) { }
+		public virtual void Emit(System.Reflection.Emit.OpCode opcode, System.Reflection.Emit.SignatureHelper signature) { }
+		public virtual void Emit(System.Reflection.Emit.OpCode opcode, System.Reflection.FieldInfo field) { }
+		public virtual void Emit(System.Reflection.Emit.OpCode opcode, System.Reflection.MethodInfo meth) { }
+		[System.CLSCompliantAttribute(false)]
+		public void Emit(System.Reflection.Emit.OpCode opcode, sbyte arg) { }
+		public virtual void Emit(System.Reflection.Emit.OpCode opcode, float arg) { }
+		public virtual void Emit(System.Reflection.Emit.OpCode opcode, string str) { }
+		public virtual void Emit(System.Reflection.Emit.OpCode opcode, System.Type cls) { }
+		public virtual void EmitCall(System.Reflection.Emit.OpCode opcode, System.Reflection.MethodInfo methodInfo, System.Type[] optionalParameterTypes) { }
+		public virtual void EmitCalli(System.Reflection.Emit.OpCode opcode, System.Reflection.CallingConventions callingConvention, System.Type returnType, System.Type[] parameterTypes, System.Type[] optionalParameterTypes) { }
+		public virtual void EmitWriteLine(System.Reflection.Emit.LocalBuilder localBuilder) { }
+		public virtual void EmitWriteLine(System.Reflection.FieldInfo fld) { }
+		public virtual void EmitWriteLine(string value) { }
+		public virtual void EndExceptionBlock() { }
+		public virtual void EndScope() { }
+		public virtual void MarkLabel(System.Reflection.Emit.Label loc) { }
+		public virtual void ThrowException(System.Type excType) { }
+		public virtual void UsingNamespace(string usingNamespace) { }
+	}
+	public sealed partial class LocalBuilder : System.Reflection.LocalVariableInfo
+	{
+		internal LocalBuilder() { }
+		public override bool IsPinned { get { throw null; } }
+		public override int LocalIndex { get { throw null; } }
+		public override System.Type LocalType { get { throw null; } }
+	}
+	public partial class ParameterBuilder
+	{
+		internal ParameterBuilder() { }
+		public virtual int Attributes { get { throw null; } }
+		public bool IsIn { get { throw null; } }
+		public bool IsOptional { get { throw null; } }
+		public bool IsOut { get { throw null; } }
+		public virtual string Name { get { throw null; } }
+		public virtual int Position { get { throw null; } }
+		public virtual void SetConstant(object defaultValue) { }
+		public void SetCustomAttribute(System.Reflection.ConstructorInfo con, byte[] binaryAttribute) { }
+		public void SetCustomAttribute(System.Reflection.Emit.CustomAttributeBuilder customBuilder) { }
+	}
+    public sealed partial class SignatureHelper
+    {
+        internal SignatureHelper() { }
+        public void AddArgument(System.Type clsArgument) { }
+        public void AddArgument(System.Type argument, bool pinned) { }
+        public void AddArgument(System.Type argument, System.Type[] requiredCustomModifiers, System.Type[] optionalCustomModifiers) { }
+        public void AddArguments(System.Type[] arguments, System.Type[][] requiredCustomModifiers, System.Type[][] optionalCustomModifiers) { }
+        public void AddSentinel() { }
+        public override bool Equals(object obj) { throw null; }
+        public static System.Reflection.Emit.SignatureHelper GetFieldSigHelper(System.Reflection.Module mod) { throw null; }
+        public override int GetHashCode() { throw null; }
+        public static System.Reflection.Emit.SignatureHelper GetLocalVarSigHelper() { throw null; }
+        public static System.Reflection.Emit.SignatureHelper GetLocalVarSigHelper(System.Reflection.Module mod) { throw null; }
+        public static System.Reflection.Emit.SignatureHelper GetMethodSigHelper(System.Reflection.CallingConventions callingConvention, System.Type returnType) { throw null; }
+        public static System.Reflection.Emit.SignatureHelper GetMethodSigHelper(System.Reflection.Module mod, System.Reflection.CallingConventions callingConvention, System.Type returnType) { throw null; }
+        public static System.Reflection.Emit.SignatureHelper GetMethodSigHelper(System.Reflection.Module mod, System.Type returnType, System.Type[] parameterTypes) { throw null; }
+        public static System.Reflection.Emit.SignatureHelper GetPropertySigHelper(System.Reflection.Module mod, System.Reflection.CallingConventions callingConvention, System.Type returnType, System.Type[] requiredReturnTypeCustomModifiers, System.Type[] optionalReturnTypeCustomModifiers, System.Type[] parameterTypes, System.Type[][] requiredParameterTypeCustomModifiers, System.Type[][] optionalParameterTypeCustomModifiers) { throw null; }
+        public static System.Reflection.Emit.SignatureHelper GetPropertySigHelper(System.Reflection.Module mod, System.Type returnType, System.Type[] parameterTypes) { throw null; }
+        public static System.Reflection.Emit.SignatureHelper GetPropertySigHelper(System.Reflection.Module mod, System.Type returnType, System.Type[] requiredReturnTypeCustomModifiers, System.Type[] optionalReturnTypeCustomModifiers, System.Type[] parameterTypes, System.Type[][] requiredParameterTypeCustomModifiers, System.Type[][] optionalParameterTypeCustomModifiers) { throw null; }
+        public byte[] GetSignature() { throw null; }
+        public override string ToString() { throw null; }
+    }
+
+    public sealed partial class AssemblyBuilder : System.Reflection.Assembly
+    {
+        internal AssemblyBuilder() { }
+        public override string FullName { get { throw null; } }
+        public override bool IsDynamic { get { throw null; } }
+        public override System.Reflection.Module ManifestModule { get { throw null; } }
+        public static System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly(System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access) { throw null; }
+        public static System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly(System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, System.Collections.Generic.IEnumerable<System.Reflection.Emit.CustomAttributeBuilder> assemblyAttributes) { throw null; }
+        public System.Reflection.Emit.ModuleBuilder DefineDynamicModule(string name) { throw null; }
+        public override bool Equals(object obj) { throw null; }
+        public System.Reflection.Emit.ModuleBuilder GetDynamicModule(string name) { throw null; }
+        public override int GetHashCode() { throw null; }
+        public override System.Reflection.ManifestResourceInfo GetManifestResourceInfo(string resourceName) { throw null; }
+        public override string[] GetManifestResourceNames() { throw null; }
+        public override System.IO.Stream GetManifestResourceStream(string name) { throw null; }
+        public void SetCustomAttribute(System.Reflection.ConstructorInfo con, byte[] binaryAttribute) { }
+        public void SetCustomAttribute(System.Reflection.Emit.CustomAttributeBuilder customBuilder) { }
+    }
+
+    public sealed partial class ConstructorBuilder : System.Reflection.ConstructorInfo
+    {
+        internal ConstructorBuilder() { }
+        public override System.Reflection.MethodAttributes Attributes { get { throw null; } }
+        public override System.Reflection.CallingConventions CallingConvention { get { throw null; } }
+        public override System.Type DeclaringType { get { throw null; } }
+        public bool InitLocals { get { throw null; } set { } }
+        public override System.RuntimeMethodHandle MethodHandle { get { throw null; } }
+        public override System.Reflection.Module Module { get { throw null; } }
+        public override string Name { get { throw null; } }
+        public override System.Type ReflectedType { get { throw null; } }
+        public System.Reflection.Emit.ParameterBuilder DefineParameter(int iSequence, System.Reflection.ParameterAttributes attributes, string strParamName) { throw null; }
+        public override object[] GetCustomAttributes(bool inherit) { throw null; }
+        public override object[] GetCustomAttributes(System.Type attributeType, bool inherit) { throw null; }
+        public System.Reflection.Emit.ILGenerator GetILGenerator() { throw null; }
+        public System.Reflection.Emit.ILGenerator GetILGenerator(int streamSize) { throw null; }
+        public override System.Reflection.MethodImplAttributes GetMethodImplementationFlags() { throw null; }
+        public override System.Reflection.ParameterInfo[] GetParameters() { throw null; }
+        public override object Invoke(object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object[] parameters, System.Globalization.CultureInfo culture) { throw null; }
+        public override object Invoke(System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object[] parameters, System.Globalization.CultureInfo culture) { throw null; }
+        public override bool IsDefined(System.Type attributeType, bool inherit) { throw null; }
+        public void SetCustomAttribute(System.Reflection.ConstructorInfo con, byte[] binaryAttribute) { }
+        public void SetCustomAttribute(System.Reflection.Emit.CustomAttributeBuilder customBuilder) { }
+        public void SetImplementationFlags(System.Reflection.MethodImplAttributes attributes) { }
+        public override string ToString() { throw null; }
+    }
+    public sealed partial class EnumBuilder : System.Type
+    {
+        internal EnumBuilder() { }
+        public override System.Reflection.Assembly Assembly { get { throw null; } }
+        public override string AssemblyQualifiedName { get { throw null; } }
+        public override System.Type BaseType { get { throw null; } }
+        public override System.Type DeclaringType { get { throw null; } }
+        public override string FullName { get { throw null; } }
+        public override System.Guid GUID { get { throw null; } }
+        public override bool IsConstructedGenericType { get { throw null; } }
+        public override System.Reflection.Module Module { get { throw null; } }
+        public override string Name { get { throw null; } }
+        public override string Namespace { get { throw null; } }
+        public override System.Type ReflectedType { get { throw null; } }
+        public override System.RuntimeTypeHandle TypeHandle { get { throw null; } }
+        public System.Reflection.Emit.FieldBuilder UnderlyingField { get { throw null; } }
+        public override System.Type UnderlyingSystemType { get { throw null; } }
+        public System.Reflection.TypeInfo CreateTypeInfo() { throw null; }
+        public System.Reflection.Emit.FieldBuilder DefineLiteral(string literalName, object literalValue) { throw null; }
+        protected override System.Reflection.TypeAttributes GetAttributeFlagsImpl() { throw null; }
+        protected override System.Reflection.ConstructorInfo GetConstructorImpl(System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Reflection.CallingConventions callConvention, System.Type[] types, System.Reflection.ParameterModifier[] modifiers) { throw null; }
+        public override System.Reflection.ConstructorInfo[] GetConstructors(System.Reflection.BindingFlags bindingAttr) { throw null; }
+        public override object[] GetCustomAttributes(bool inherit) { throw null; }
+        public override object[] GetCustomAttributes(System.Type attributeType, bool inherit) { throw null; }
+        public override System.Type GetElementType() { throw null; }
+        public override System.Type GetEnumUnderlyingType() { throw null; }
+        public override System.Reflection.EventInfo GetEvent(string name, System.Reflection.BindingFlags bindingAttr) { throw null; }
+        public override System.Reflection.EventInfo[] GetEvents() { throw null; }
+        public override System.Reflection.EventInfo[] GetEvents(System.Reflection.BindingFlags bindingAttr) { throw null; }
+        public override System.Reflection.FieldInfo GetField(string name, System.Reflection.BindingFlags bindingAttr) { throw null; }
+        public override System.Reflection.FieldInfo[] GetFields(System.Reflection.BindingFlags bindingAttr) { throw null; }
+        public override System.Type GetInterface(string name, bool ignoreCase) { throw null; }
+        public override System.Reflection.InterfaceMapping GetInterfaceMap(System.Type interfaceType) { throw null; }
+        public override System.Type[] GetInterfaces() { throw null; }
+        public override System.Reflection.MemberInfo[] GetMember(string name, System.Reflection.MemberTypes type, System.Reflection.BindingFlags bindingAttr) { throw null; }
+        public override System.Reflection.MemberInfo[] GetMembers(System.Reflection.BindingFlags bindingAttr) { throw null; }
+        protected override System.Reflection.MethodInfo GetMethodImpl(string name, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Reflection.CallingConventions callConvention, System.Type[] types, System.Reflection.ParameterModifier[] modifiers) { throw null; }
+        public override System.Reflection.MethodInfo[] GetMethods(System.Reflection.BindingFlags bindingAttr) { throw null; }
+        public override System.Type GetNestedType(string name, System.Reflection.BindingFlags bindingAttr) { throw null; }
+        public override System.Type[] GetNestedTypes(System.Reflection.BindingFlags bindingAttr) { throw null; }
+        public override System.Reflection.PropertyInfo[] GetProperties(System.Reflection.BindingFlags bindingAttr) { throw null; }
+        protected override System.Reflection.PropertyInfo GetPropertyImpl(string name, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Type returnType, System.Type[] types, System.Reflection.ParameterModifier[] modifiers) { throw null; }
+        protected override bool HasElementTypeImpl() { throw null; }
+        public override object InvokeMember(string name, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object target, object[] args, System.Reflection.ParameterModifier[] modifiers, System.Globalization.CultureInfo culture, string[] namedParameters) { throw null; }
+        protected override bool IsArrayImpl() { throw null; }
+        protected override bool IsByRefImpl() { throw null; }
+        protected override bool IsCOMObjectImpl() { throw null; }
+        public override bool IsDefined(System.Type attributeType, bool inherit) { throw null; }
+        protected override bool IsPointerImpl() { throw null; }
+        protected override bool IsPrimitiveImpl() { throw null; }
+        protected override bool IsValueTypeImpl() { throw null; }
+        public override System.Type MakeArrayType() { throw null; }
+        public override System.Type MakeArrayType(int rank) { throw null; }
+        public override System.Type MakeByRefType() { throw null; }
+        public override System.Type MakePointerType() { throw null; }
+        public void SetCustomAttribute(System.Reflection.ConstructorInfo con, byte[] binaryAttribute) { }
+        public void SetCustomAttribute(System.Reflection.Emit.CustomAttributeBuilder customBuilder) { }
+    }
+    public sealed partial class EventBuilder
+    {
+        internal EventBuilder() { }
+        public void AddOtherMethod(System.Reflection.Emit.MethodBuilder mdBuilder) { }
+        public void SetAddOnMethod(System.Reflection.Emit.MethodBuilder mdBuilder) { }
+        public void SetCustomAttribute(System.Reflection.ConstructorInfo con, byte[] binaryAttribute) { }
+        public void SetCustomAttribute(System.Reflection.Emit.CustomAttributeBuilder customBuilder) { }
+        public void SetRaiseMethod(System.Reflection.Emit.MethodBuilder mdBuilder) { }
+        public void SetRemoveOnMethod(System.Reflection.Emit.MethodBuilder mdBuilder) { }
+    }
+    public sealed partial class FieldBuilder : System.Reflection.FieldInfo
+    {
+        internal FieldBuilder() { }
+        public override System.Reflection.FieldAttributes Attributes { get { throw null; } }
+        public override System.Type DeclaringType { get { throw null; } }
+        public override System.RuntimeFieldHandle FieldHandle { get { throw null; } }
+        public override System.Type FieldType { get { throw null; } }
+        public override string Name { get { throw null; } }
+        public override System.Type ReflectedType { get { throw null; } }
+        public override object[] GetCustomAttributes(bool inherit) { throw null; }
+        public override object[] GetCustomAttributes(System.Type attributeType, bool inherit) { throw null; }
+        public override object GetValue(object obj) { throw null; }
+        public override bool IsDefined(System.Type attributeType, bool inherit) { throw null; }
+        public void SetConstant(object defaultValue) { }
+        public void SetCustomAttribute(System.Reflection.ConstructorInfo con, byte[] binaryAttribute) { }
+        public void SetCustomAttribute(System.Reflection.Emit.CustomAttributeBuilder customBuilder) { }
+        public void SetOffset(int iOffset) { }
+        public override void SetValue(object obj, object val, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Globalization.CultureInfo culture) { }
+    }
+    public sealed partial class GenericTypeParameterBuilder : System.Type
+    {
+        internal GenericTypeParameterBuilder() { }
+        public override System.Reflection.Assembly Assembly { get { throw null; } }
+        public override string AssemblyQualifiedName { get { throw null; } }
+        public override System.Type BaseType { get { throw null; } }
+        public override bool ContainsGenericParameters { get { throw null; } }
+        public override System.Reflection.MethodBase DeclaringMethod { get { throw null; } }
+        public override System.Type DeclaringType { get { throw null; } }
+        public override string FullName { get { throw null; } }
+        public override System.Reflection.GenericParameterAttributes GenericParameterAttributes { get { throw null; } }
+        public override int GenericParameterPosition { get { throw null; } }
+        public override System.Guid GUID { get { throw null; } }
+        public override bool IsConstructedGenericType { get { throw null; } }
+        public override bool IsGenericParameter { get { throw null; } }
+        public override bool IsGenericType { get { throw null; } }
+        public override bool IsGenericTypeDefinition { get { throw null; } }
+        public override System.Reflection.Module Module { get { throw null; } }
+        public override string Name { get { throw null; } }
+        public override string Namespace { get { throw null; } }
+        public override System.Type ReflectedType { get { throw null; } }
+        public override System.RuntimeTypeHandle TypeHandle { get { throw null; } }
+        public override System.Type UnderlyingSystemType { get { throw null; } }
+        public override bool Equals(object o) { throw null; }
+        protected override System.Reflection.TypeAttributes GetAttributeFlagsImpl() { throw null; }
+        protected override System.Reflection.ConstructorInfo GetConstructorImpl(System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Reflection.CallingConventions callConvention, System.Type[] types, System.Reflection.ParameterModifier[] modifiers) { throw null; }
+        public override System.Reflection.ConstructorInfo[] GetConstructors(System.Reflection.BindingFlags bindingAttr) { throw null; }
+        public override object[] GetCustomAttributes(bool inherit) { throw null; }
+        public override object[] GetCustomAttributes(System.Type attributeType, bool inherit) { throw null; }
+        public override System.Type GetElementType() { throw null; }
+        public override System.Reflection.EventInfo GetEvent(string name, System.Reflection.BindingFlags bindingAttr) { throw null; }
+        public override System.Reflection.EventInfo[] GetEvents() { throw null; }
+        public override System.Reflection.EventInfo[] GetEvents(System.Reflection.BindingFlags bindingAttr) { throw null; }
+        public override System.Reflection.FieldInfo GetField(string name, System.Reflection.BindingFlags bindingAttr) { throw null; }
+        public override System.Reflection.FieldInfo[] GetFields(System.Reflection.BindingFlags bindingAttr) { throw null; }
+        public override System.Type[] GetGenericArguments() { throw null; }
+        public override System.Type GetGenericTypeDefinition() { throw null; }
+        public override int GetHashCode() { throw null; }
+        public override System.Type GetInterface(string name, bool ignoreCase) { throw null; }
+        public override System.Reflection.InterfaceMapping GetInterfaceMap(System.Type interfaceType) { throw null; }
+        public override System.Type[] GetInterfaces() { throw null; }
+        public override System.Reflection.MemberInfo[] GetMember(string name, System.Reflection.MemberTypes type, System.Reflection.BindingFlags bindingAttr) { throw null; }
+        public override System.Reflection.MemberInfo[] GetMembers(System.Reflection.BindingFlags bindingAttr) { throw null; }
+        protected override System.Reflection.MethodInfo GetMethodImpl(string name, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Reflection.CallingConventions callConvention, System.Type[] types, System.Reflection.ParameterModifier[] modifiers) { throw null; }
+        public override System.Reflection.MethodInfo[] GetMethods(System.Reflection.BindingFlags bindingAttr) { throw null; }
+        public override System.Type GetNestedType(string name, System.Reflection.BindingFlags bindingAttr) { throw null; }
+        public override System.Type[] GetNestedTypes(System.Reflection.BindingFlags bindingAttr) { throw null; }
+        public override System.Reflection.PropertyInfo[] GetProperties(System.Reflection.BindingFlags bindingAttr) { throw null; }
+        protected override System.Reflection.PropertyInfo GetPropertyImpl(string name, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Type returnType, System.Type[] types, System.Reflection.ParameterModifier[] modifiers) { throw null; }
+        protected override bool HasElementTypeImpl() { throw null; }
+        public override object InvokeMember(string name, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object target, object[] args, System.Reflection.ParameterModifier[] modifiers, System.Globalization.CultureInfo culture, string[] namedParameters) { throw null; }
+        protected override bool IsArrayImpl() { throw null; }
+        public override bool IsAssignableFrom(System.Type c) { throw null; }
+        protected override bool IsByRefImpl() { throw null; }
+        protected override bool IsCOMObjectImpl() { throw null; }
+        public override bool IsDefined(System.Type attributeType, bool inherit) { throw null; }
+        protected override bool IsPointerImpl() { throw null; }
+        protected override bool IsPrimitiveImpl() { throw null; }
+        public override bool IsSubclassOf(System.Type c) { throw null; }
+        protected override bool IsValueTypeImpl() { throw null; }
+        public override System.Type MakeArrayType() { throw null; }
+        public override System.Type MakeArrayType(int rank) { throw null; }
+        public override System.Type MakeByRefType() { throw null; }
+        public override System.Type MakeGenericType(params System.Type[] typeArguments) { throw null; }
+        public override System.Type MakePointerType() { throw null; }
+        public void SetBaseTypeConstraint(System.Type baseTypeConstraint) { }
+        public void SetCustomAttribute(System.Reflection.ConstructorInfo con, byte[] binaryAttribute) { }
+        public void SetCustomAttribute(System.Reflection.Emit.CustomAttributeBuilder customBuilder) { }
+        public void SetGenericParameterAttributes(System.Reflection.GenericParameterAttributes genericParameterAttributes) { }
+        public void SetInterfaceConstraints(params System.Type[] interfaceConstraints) { }
+        public override string ToString() { throw null; }
+    }
+    public sealed partial class MethodBuilder : System.Reflection.MethodInfo
+    {
+        internal MethodBuilder() { }
+        public override System.Reflection.MethodAttributes Attributes { get { throw null; } }
+        public override System.Reflection.CallingConventions CallingConvention { get { throw null; } }
+        public override bool ContainsGenericParameters { get { throw null; } }
+        public override System.Type DeclaringType { get { throw null; } }
+        public bool InitLocals { get { throw null; } set { } }
+        public override bool IsGenericMethod { get { throw null; } }
+        public override bool IsGenericMethodDefinition { get { throw null; } }
+        public override System.RuntimeMethodHandle MethodHandle { get { throw null; } }
+        public override System.Reflection.Module Module { get { throw null; } }
+        public override string Name { get { throw null; } }
+        public override System.Type ReflectedType { get { throw null; } }
+        public override System.Reflection.ParameterInfo ReturnParameter { get { throw null; } }
+        public override System.Type ReturnType { get { throw null; } }
+        public override System.Reflection.ICustomAttributeProvider ReturnTypeCustomAttributes { get { throw null; } }
+        public System.Reflection.Emit.GenericTypeParameterBuilder[] DefineGenericParameters(params string[] names) { throw null; }
+        public System.Reflection.Emit.ParameterBuilder DefineParameter(int position, System.Reflection.ParameterAttributes attributes, string strParamName) { throw null; }
+        public override bool Equals(object obj) { throw null; }
+        public override System.Reflection.MethodInfo GetBaseDefinition() { throw null; }
+        public override object[] GetCustomAttributes(bool inherit) { throw null; }
+        public override object[] GetCustomAttributes(System.Type attributeType, bool inherit) { throw null; }
+        public override System.Type[] GetGenericArguments() { throw null; }
+        public override System.Reflection.MethodInfo GetGenericMethodDefinition() { throw null; }
+        public override int GetHashCode() { throw null; }
+        public System.Reflection.Emit.ILGenerator GetILGenerator() { throw null; }
+        public System.Reflection.Emit.ILGenerator GetILGenerator(int size) { throw null; }
+        public override System.Reflection.MethodImplAttributes GetMethodImplementationFlags() { throw null; }
+        public override System.Reflection.ParameterInfo[] GetParameters() { throw null; }
+        public override object Invoke(object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object[] parameters, System.Globalization.CultureInfo culture) { throw null; }
+        public override bool IsDefined(System.Type attributeType, bool inherit) { throw null; }
+        public override System.Reflection.MethodInfo MakeGenericMethod(params System.Type[] typeArguments) { throw null; }
+        public void SetCustomAttribute(System.Reflection.ConstructorInfo con, byte[] binaryAttribute) { }
+        public void SetCustomAttribute(System.Reflection.Emit.CustomAttributeBuilder customBuilder) { }
+        public void SetImplementationFlags(System.Reflection.MethodImplAttributes attributes) { }
+        public void SetParameters(params System.Type[] parameterTypes) { }
+        public void SetReturnType(System.Type returnType) { }
+        public void SetSignature(System.Type returnType, System.Type[] returnTypeRequiredCustomModifiers, System.Type[] returnTypeOptionalCustomModifiers, System.Type[] parameterTypes, System.Type[][] parameterTypeRequiredCustomModifiers, System.Type[][] parameterTypeOptionalCustomModifiers) { }
+        public override string ToString() { throw null; }
+    }
+    public partial class ModuleBuilder : System.Reflection.Module
+    {
+        internal ModuleBuilder() { }
+        public override System.Reflection.Assembly Assembly { get { throw null; } }
+        public override string FullyQualifiedName { get { throw null; } }
+        public override string Name { get { throw null; } }
+        public void CreateGlobalFunctions() { }
+        public System.Reflection.Emit.EnumBuilder DefineEnum(string name, System.Reflection.TypeAttributes visibility, System.Type underlyingType) { throw null; }
+        public System.Reflection.Emit.MethodBuilder DefineGlobalMethod(string name, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, System.Type returnType, System.Type[] parameterTypes) { throw null; }
+        public System.Reflection.Emit.MethodBuilder DefineGlobalMethod(string name, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, System.Type returnType, System.Type[] requiredReturnTypeCustomModifiers, System.Type[] optionalReturnTypeCustomModifiers, System.Type[] parameterTypes, System.Type[][] requiredParameterTypeCustomModifiers, System.Type[][] optionalParameterTypeCustomModifiers) { throw null; }
+        public System.Reflection.Emit.MethodBuilder DefineGlobalMethod(string name, System.Reflection.MethodAttributes attributes, System.Type returnType, System.Type[] parameterTypes) { throw null; }
+        public System.Reflection.Emit.FieldBuilder DefineInitializedData(string name, byte[] data, System.Reflection.FieldAttributes attributes) { throw null; }
+        public System.Reflection.Emit.TypeBuilder DefineType(string name) { throw null; }
+        public System.Reflection.Emit.TypeBuilder DefineType(string name, System.Reflection.TypeAttributes attr) { throw null; }
+        public System.Reflection.Emit.TypeBuilder DefineType(string name, System.Reflection.TypeAttributes attr, System.Type parent) { throw null; }
+        public System.Reflection.Emit.TypeBuilder DefineType(string name, System.Reflection.TypeAttributes attr, System.Type parent, int typesize) { throw null; }
+        public System.Reflection.Emit.TypeBuilder DefineType(string name, System.Reflection.TypeAttributes attr, System.Type parent, System.Reflection.Emit.PackingSize packsize) { throw null; }
+        public System.Reflection.Emit.TypeBuilder DefineType(string name, System.Reflection.TypeAttributes attr, System.Type parent, System.Reflection.Emit.PackingSize packingSize, int typesize) { throw null; }
+        public System.Reflection.Emit.TypeBuilder DefineType(string name, System.Reflection.TypeAttributes attr, System.Type parent, System.Type[] interfaces) { throw null; }
+        public System.Reflection.Emit.FieldBuilder DefineUninitializedData(string name, int size, System.Reflection.FieldAttributes attributes) { throw null; }
+        public override bool Equals(object obj) { throw null; }
+        public System.Reflection.MethodInfo GetArrayMethod(System.Type arrayClass, string methodName, System.Reflection.CallingConventions callingConvention, System.Type returnType, System.Type[] parameterTypes) { throw null; }
+        public override int GetHashCode() { throw null; }
+        public void SetCustomAttribute(System.Reflection.ConstructorInfo con, byte[] binaryAttribute) { }
+        public void SetCustomAttribute(System.Reflection.Emit.CustomAttributeBuilder customBuilder) { }
+    }
+    public sealed partial class PropertyBuilder : System.Reflection.PropertyInfo
+    {
+        internal PropertyBuilder() { }
+        public override System.Reflection.PropertyAttributes Attributes { get { throw null; } }
+        public override bool CanRead { get { throw null; } }
+        public override bool CanWrite { get { throw null; } }
+        public override System.Type DeclaringType { get { throw null; } }
+        public override System.Reflection.Module Module { get { throw null; } }
+        public override string Name { get { throw null; } }
+        public override System.Type PropertyType { get { throw null; } }
+        public override System.Type ReflectedType { get { throw null; } }
+        public void AddOtherMethod(System.Reflection.Emit.MethodBuilder mdBuilder) { }
+        public override System.Reflection.MethodInfo[] GetAccessors(bool nonPublic) { throw null; }
+        public override object[] GetCustomAttributes(bool inherit) { throw null; }
+        public override object[] GetCustomAttributes(System.Type attributeType, bool inherit) { throw null; }
+        public override System.Reflection.MethodInfo GetGetMethod(bool nonPublic) { throw null; }
+        public override System.Reflection.ParameterInfo[] GetIndexParameters() { throw null; }
+        public override System.Reflection.MethodInfo GetSetMethod(bool nonPublic) { throw null; }
+        public override object GetValue(object obj, object[] index) { throw null; }
+        public override object GetValue(object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object[] index, System.Globalization.CultureInfo culture) { throw null; }
+        public override bool IsDefined(System.Type attributeType, bool inherit) { throw null; }
+        public void SetConstant(object defaultValue) { }
+        public void SetCustomAttribute(System.Reflection.ConstructorInfo con, byte[] binaryAttribute) { }
+        public void SetCustomAttribute(System.Reflection.Emit.CustomAttributeBuilder customBuilder) { }
+        public void SetGetMethod(System.Reflection.Emit.MethodBuilder mdBuilder) { }
+        public void SetSetMethod(System.Reflection.Emit.MethodBuilder mdBuilder) { }
+        public override void SetValue(object obj, object value, object[] index) { }
+        public override void SetValue(object obj, object value, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object[] index, System.Globalization.CultureInfo culture) { }
+    }
+    public sealed partial class TypeBuilder : System.Type
+    {
+        internal TypeBuilder() { }
+        public const int UnspecifiedTypeSize = 0;
+        public override System.Reflection.Assembly Assembly { get { throw null; } }
+        public override string AssemblyQualifiedName { get { throw null; } }
+        public override System.Type BaseType { get { throw null; } }
+        public override System.Reflection.MethodBase DeclaringMethod { get { throw null; } }
+        public override System.Type DeclaringType { get { throw null; } }
+        public override string FullName { get { throw null; } }
+        public override System.Reflection.GenericParameterAttributes GenericParameterAttributes { get { throw null; } }
+        public override int GenericParameterPosition { get { throw null; } }
+        public override System.Guid GUID { get { throw null; } }
+        public override bool IsConstructedGenericType { get { throw null; } }
+        public override bool IsGenericParameter { get { throw null; } }
+        public override bool IsGenericType { get { throw null; } }
+        public override bool IsGenericTypeDefinition { get { throw null; } }
+        public override bool IsSecurityCritical { get { throw null; } }
+        public override bool IsSecuritySafeCritical { get { throw null; } }
+        public override bool IsSecurityTransparent { get { throw null; } }
+        public override System.Reflection.Module Module { get { throw null; } }
+        public override string Name { get { throw null; } }
+        public override string Namespace { get { throw null; } }
+        public System.Reflection.Emit.PackingSize PackingSize { get { throw null; } }
+        public override System.Type ReflectedType { get { throw null; } }
+        public int Size { get { throw null; } }
+        public override System.RuntimeTypeHandle TypeHandle { get { throw null; } }
+        public override System.Type UnderlyingSystemType { get { throw null; } }
+        public void AddInterfaceImplementation(System.Type interfaceType) { }
+        public System.Reflection.TypeInfo CreateTypeInfo() { throw null; }
+        public System.Reflection.Emit.ConstructorBuilder DefineConstructor(System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, System.Type[] parameterTypes) { throw null; }
+        public System.Reflection.Emit.ConstructorBuilder DefineConstructor(System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, System.Type[] parameterTypes, System.Type[][] requiredCustomModifiers, System.Type[][] optionalCustomModifiers) { throw null; }
+        public System.Reflection.Emit.ConstructorBuilder DefineDefaultConstructor(System.Reflection.MethodAttributes attributes) { throw null; }
+        public System.Reflection.Emit.EventBuilder DefineEvent(string name, System.Reflection.EventAttributes attributes, System.Type eventtype) { throw null; }
+        public System.Reflection.Emit.FieldBuilder DefineField(string fieldName, System.Type type, System.Reflection.FieldAttributes attributes) { throw null; }
+        public System.Reflection.Emit.FieldBuilder DefineField(string fieldName, System.Type type, System.Type[] requiredCustomModifiers, System.Type[] optionalCustomModifiers, System.Reflection.FieldAttributes attributes) { throw null; }
+        public System.Reflection.Emit.GenericTypeParameterBuilder[] DefineGenericParameters(params string[] names) { throw null; }
+        public System.Reflection.Emit.FieldBuilder DefineInitializedData(string name, byte[] data, System.Reflection.FieldAttributes attributes) { throw null; }
+        public System.Reflection.Emit.MethodBuilder DefineMethod(string name, System.Reflection.MethodAttributes attributes) { throw null; }
+        public System.Reflection.Emit.MethodBuilder DefineMethod(string name, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention) { throw null; }
+        public System.Reflection.Emit.MethodBuilder DefineMethod(string name, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, System.Type returnType, System.Type[] parameterTypes) { throw null; }
+        public System.Reflection.Emit.MethodBuilder DefineMethod(string name, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, System.Type returnType, System.Type[] returnTypeRequiredCustomModifiers, System.Type[] returnTypeOptionalCustomModifiers, System.Type[] parameterTypes, System.Type[][] parameterTypeRequiredCustomModifiers, System.Type[][] parameterTypeOptionalCustomModifiers) { throw null; }
+        public System.Reflection.Emit.MethodBuilder DefineMethod(string name, System.Reflection.MethodAttributes attributes, System.Type returnType, System.Type[] parameterTypes) { throw null; }
+        public void DefineMethodOverride(System.Reflection.MethodInfo methodInfoBody, System.Reflection.MethodInfo methodInfoDeclaration) { }
+        public System.Reflection.Emit.TypeBuilder DefineNestedType(string name) { throw null; }
+        public System.Reflection.Emit.TypeBuilder DefineNestedType(string name, System.Reflection.TypeAttributes attr) { throw null; }
+        public System.Reflection.Emit.TypeBuilder DefineNestedType(string name, System.Reflection.TypeAttributes attr, System.Type parent) { throw null; }
+        public System.Reflection.Emit.TypeBuilder DefineNestedType(string name, System.Reflection.TypeAttributes attr, System.Type parent, int typeSize) { throw null; }
+        public System.Reflection.Emit.TypeBuilder DefineNestedType(string name, System.Reflection.TypeAttributes attr, System.Type parent, System.Reflection.Emit.PackingSize packSize) { throw null; }
+        public System.Reflection.Emit.TypeBuilder DefineNestedType(string name, System.Reflection.TypeAttributes attr, System.Type parent, System.Reflection.Emit.PackingSize packSize, int typeSize) { throw null; }
+        public System.Reflection.Emit.TypeBuilder DefineNestedType(string name, System.Reflection.TypeAttributes attr, System.Type parent, System.Type[] interfaces) { throw null; }
+        public System.Reflection.Emit.PropertyBuilder DefineProperty(string name, System.Reflection.PropertyAttributes attributes, System.Reflection.CallingConventions callingConvention, System.Type returnType, System.Type[] parameterTypes) { throw null; }
+        public System.Reflection.Emit.PropertyBuilder DefineProperty(string name, System.Reflection.PropertyAttributes attributes, System.Reflection.CallingConventions callingConvention, System.Type returnType, System.Type[] returnTypeRequiredCustomModifiers, System.Type[] returnTypeOptionalCustomModifiers, System.Type[] parameterTypes, System.Type[][] parameterTypeRequiredCustomModifiers, System.Type[][] parameterTypeOptionalCustomModifiers) { throw null; }
+        public System.Reflection.Emit.PropertyBuilder DefineProperty(string name, System.Reflection.PropertyAttributes attributes, System.Type returnType, System.Type[] parameterTypes) { throw null; }
+        public System.Reflection.Emit.PropertyBuilder DefineProperty(string name, System.Reflection.PropertyAttributes attributes, System.Type returnType, System.Type[] returnTypeRequiredCustomModifiers, System.Type[] returnTypeOptionalCustomModifiers, System.Type[] parameterTypes, System.Type[][] parameterTypeRequiredCustomModifiers, System.Type[][] parameterTypeOptionalCustomModifiers) { throw null; }
+        public System.Reflection.Emit.ConstructorBuilder DefineTypeInitializer() { throw null; }
+        public System.Reflection.Emit.FieldBuilder DefineUninitializedData(string name, int size, System.Reflection.FieldAttributes attributes) { throw null; }
+        protected override System.Reflection.TypeAttributes GetAttributeFlagsImpl() { throw null; }
+        public static System.Reflection.ConstructorInfo GetConstructor(System.Type type, System.Reflection.ConstructorInfo constructor) { throw null; }
+        protected override System.Reflection.ConstructorInfo GetConstructorImpl(System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Reflection.CallingConventions callConvention, System.Type[] types, System.Reflection.ParameterModifier[] modifiers) { throw null; }
+        public override System.Reflection.ConstructorInfo[] GetConstructors(System.Reflection.BindingFlags bindingAttr) { throw null; }
+        public override object[] GetCustomAttributes(bool inherit) { throw null; }
+        public override object[] GetCustomAttributes(System.Type attributeType, bool inherit) { throw null; }
+        public override System.Type GetElementType() { throw null; }
+        public override System.Reflection.EventInfo GetEvent(string name, System.Reflection.BindingFlags bindingAttr) { throw null; }
+        public override System.Reflection.EventInfo[] GetEvents() { throw null; }
+        public override System.Reflection.EventInfo[] GetEvents(System.Reflection.BindingFlags bindingAttr) { throw null; }
+        public override System.Reflection.FieldInfo GetField(string name, System.Reflection.BindingFlags bindingAttr) { throw null; }
+        public static System.Reflection.FieldInfo GetField(System.Type type, System.Reflection.FieldInfo field) { throw null; }
+        public override System.Reflection.FieldInfo[] GetFields(System.Reflection.BindingFlags bindingAttr) { throw null; }
+        public override System.Type[] GetGenericArguments() { throw null; }
+        public override System.Type GetGenericTypeDefinition() { throw null; }
+        public override System.Type GetInterface(string name, bool ignoreCase) { throw null; }
+        public override System.Reflection.InterfaceMapping GetInterfaceMap(System.Type interfaceType) { throw null; }
+        public override System.Type[] GetInterfaces() { throw null; }
+        public override System.Reflection.MemberInfo[] GetMember(string name, System.Reflection.MemberTypes type, System.Reflection.BindingFlags bindingAttr) { throw null; }
+        public override System.Reflection.MemberInfo[] GetMembers(System.Reflection.BindingFlags bindingAttr) { throw null; }
+        public static System.Reflection.MethodInfo GetMethod(System.Type type, System.Reflection.MethodInfo method) { throw null; }
+        protected override System.Reflection.MethodInfo GetMethodImpl(string name, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Reflection.CallingConventions callConvention, System.Type[] types, System.Reflection.ParameterModifier[] modifiers) { throw null; }
+        public override System.Reflection.MethodInfo[] GetMethods(System.Reflection.BindingFlags bindingAttr) { throw null; }
+        public override System.Type GetNestedType(string name, System.Reflection.BindingFlags bindingAttr) { throw null; }
+        public override System.Type[] GetNestedTypes(System.Reflection.BindingFlags bindingAttr) { throw null; }
+        public override System.Reflection.PropertyInfo[] GetProperties(System.Reflection.BindingFlags bindingAttr) { throw null; }
+        protected override System.Reflection.PropertyInfo GetPropertyImpl(string name, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Type returnType, System.Type[] types, System.Reflection.ParameterModifier[] modifiers) { throw null; }
+        protected override bool HasElementTypeImpl() { throw null; }
+        public override object InvokeMember(string name, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object target, object[] args, System.Reflection.ParameterModifier[] modifiers, System.Globalization.CultureInfo culture, string[] namedParameters) { throw null; }
+        protected override bool IsArrayImpl() { throw null; }
+        public override bool IsAssignableFrom(System.Type c) { throw null; }
+        protected override bool IsByRefImpl() { throw null; }
+        protected override bool IsCOMObjectImpl() { throw null; }
+        public bool IsCreated() { throw null; }
+        public override bool IsDefined(System.Type attributeType, bool inherit) { throw null; }
+        protected override bool IsPointerImpl() { throw null; }
+        protected override bool IsPrimitiveImpl() { throw null; }
+        public override bool IsSubclassOf(System.Type c) { throw null; }
+        public override System.Type MakeArrayType() { throw null; }
+        public override System.Type MakeArrayType(int rank) { throw null; }
+        public override System.Type MakeByRefType() { throw null; }
+        public override System.Type MakeGenericType(params System.Type[] typeArguments) { throw null; }
+        public override System.Type MakePointerType() { throw null; }
+        public void SetCustomAttribute(System.Reflection.ConstructorInfo con, byte[] binaryAttribute) { }
+        public void SetCustomAttribute(System.Reflection.Emit.CustomAttributeBuilder customBuilder) { }
+        public void SetParent(System.Type parent) { }
+        public override string ToString() { throw null; }
+    }
+
+    public sealed partial class DynamicMethod : System.Reflection.MethodInfo
+    {
+        public DynamicMethod(string name, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, System.Type returnType, System.Type[] parameterTypes, System.Reflection.Module m, bool skipVisibility) { }
+        public DynamicMethod(string name, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, System.Type returnType, System.Type[] parameterTypes, System.Type owner, bool skipVisibility) { }
+        public DynamicMethod(string name, System.Type returnType, System.Type[] parameterTypes) { }
+        public DynamicMethod(string name, System.Type returnType, System.Type[] parameterTypes, bool restrictedSkipVisibility) { }
+        public DynamicMethod(string name, System.Type returnType, System.Type[] parameterTypes, System.Reflection.Module m) { }
+        public DynamicMethod(string name, System.Type returnType, System.Type[] parameterTypes, System.Reflection.Module m, bool skipVisibility) { }
+        public DynamicMethod(string name, System.Type returnType, System.Type[] parameterTypes, System.Type owner) { }
+        public DynamicMethod(string name, System.Type returnType, System.Type[] parameterTypes, System.Type owner, bool skipVisibility) { }
+        public override System.Reflection.MethodAttributes Attributes { get { throw null; } }
+        public override System.Reflection.CallingConventions CallingConvention { get { throw null; } }
+        public override System.Type DeclaringType { get { throw null; } }
+        public ParameterBuilder DefineParameter(int position, System.Reflection.ParameterAttributes attributes, System.String parameterName) { throw null; }
+        public bool InitLocals { get { throw null; } set { } }
+        public override System.RuntimeMethodHandle MethodHandle { get { throw null; } }
+        public override string Name { get { throw null; } }
+        public override System.Type ReflectedType { get { throw null; } }
+        public override System.Reflection.ParameterInfo ReturnParameter { get { throw null; } }
+        public override System.Type ReturnType { get { throw null; } }
+        public override System.Reflection.ICustomAttributeProvider ReturnTypeCustomAttributes { get { throw null; } }
+        public sealed override System.Delegate CreateDelegate(System.Type delegateType) { throw null; }
+        public sealed override System.Delegate CreateDelegate(System.Type delegateType, object target) { throw null; }
+        public override System.Reflection.MethodInfo GetBaseDefinition() { throw null; }
+        public override object[] GetCustomAttributes(bool inherit) { throw null; }
+        public override object[] GetCustomAttributes(System.Type attributeType, bool inherit) { throw null; }
+        public System.Reflection.Emit.ILGenerator GetILGenerator() { throw null; }
+        public System.Reflection.Emit.ILGenerator GetILGenerator(int streamSize) { throw null; }
+        public override System.Reflection.MethodImplAttributes GetMethodImplementationFlags() { throw null; }
+        public override System.Reflection.ParameterInfo[] GetParameters() { throw null; }
+        public override object Invoke(object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object[] parameters, System.Globalization.CultureInfo culture) { throw null; }
+        public override bool IsDefined(System.Type attributeType, bool inherit) { throw null; }
+        public override string ToString() { throw null; }
+    }
+
+    public sealed partial class TypeBuilder : System.Type
+    {
+        public System.Type CreateType() { throw null; }
+        public override bool IsByRefLike { get { throw null; } }
+        public override bool IsTypeDefinition { get { throw null; } }
+        public override bool IsSZArray { get { throw null; } }
+        public override bool IsVariableBoundArray { get { throw null; } }
+        public System.Reflection.Emit.MethodBuilder DefinePInvokeMethod(string name, string dllName, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, System.Type returnType, System.Type[] parameterTypes, System.Runtime.InteropServices.CallingConvention nativeCallConv, System.Runtime.InteropServices.CharSet nativeCharSet) { throw null; }
+        public System.Reflection.Emit.MethodBuilder DefinePInvokeMethod(string name, string dllName, string entryName, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, System.Type returnType, System.Type[] parameterTypes, System.Runtime.InteropServices.CallingConvention nativeCallConv, System.Runtime.InteropServices.CharSet nativeCharSet) { throw null; }
+        public System.Reflection.Emit.MethodBuilder DefinePInvokeMethod(string name, string dllName, string entryName, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, System.Type returnType, System.Type[] returnTypeRequiredCustomModifiers, System.Type[] returnTypeOptionalCustomModifiers, System.Type[] parameterTypes, System.Type[][] parameterTypeRequiredCustomModifiers, System.Type[][] parameterTypeOptionalCustomModifiers, System.Runtime.InteropServices.CallingConvention nativeCallConv, System.Runtime.InteropServices.CharSet nativeCharSet) { throw null; }
+    }
+
+    public partial class ModuleBuilder : System.Reflection.Module
+    {
+        public System.Reflection.Emit.MethodBuilder DefinePInvokeMethod(string name, string dllName, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, System.Type returnType, System.Type[] parameterTypes, System.Runtime.InteropServices.CallingConvention nativeCallConv, System.Runtime.InteropServices.CharSet nativeCharSet) { throw null; }
+        public System.Reflection.Emit.MethodBuilder DefinePInvokeMethod(string name, string dllName, string entryName, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, System.Type returnType, System.Type[] parameterTypes, System.Runtime.InteropServices.CallingConvention nativeCallConv, System.Runtime.InteropServices.CharSet nativeCharSet) { throw null; }
+    }
+
+    public partial class ILGenerator
+    {
+        public virtual void EmitCalli(System.Reflection.Emit.OpCode opcode, System.Runtime.InteropServices.CallingConvention unmanagedCallConv, Type returnType, Type[] parameterTypes) { }
+    }
+}

+ 8 - 0
mcs/class/System.Private.CoreLib/System.Reflection.Metadata/AssemblyExtensions.cs

@@ -0,0 +1,8 @@
+namespace System.Reflection.Metadata
+{
+	public static class AssemblyExtensions
+	{
+		[CLSCompliant(false)]
+		public static unsafe bool TryGetRawMetadata(this Assembly assembly, out byte* blob, out int length) => throw new NotImplementedException ();
+	}
+}

+ 35 - 0
mcs/class/System.Private.CoreLib/System.Reflection/Assembly.cs

@@ -0,0 +1,35 @@
+namespace System.Reflection
+{
+	partial class Assembly
+	{
+		public static Assembly LoadFrom (string assemblyFile)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public static Assembly GetCallingAssembly () { throw null; }
+
+		public static Assembly Load (byte[] rawAssembly, byte[] rawSymbolStore)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public static Assembly GetEntryAssembly ()
+		{
+			throw new NotImplementedException ();
+		}
+
+		public static Assembly GetExecutingAssembly () { throw null; }
+
+		public static Assembly Load (AssemblyName assemblyRef) { throw null; }
+
+		public static Assembly LoadFile (string path) { throw null; }
+
+		public static Assembly LoadFrom (string assemblyFile, byte[] hashValue, System.Configuration.Assemblies.AssemblyHashAlgorithm hashAlgorithm) { throw null; }
+
+		public static Assembly Load (string unused)
+		{
+			throw new NotImplementedException ();
+		}
+	}
+}

+ 33 - 0
mcs/class/System.Private.CoreLib/System.Reflection/AssemblyName.cs

@@ -0,0 +1,33 @@
+namespace System.Reflection
+{
+	public sealed partial class AssemblyName : System.ICloneable, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable
+	{
+		public AssemblyName() { }
+		public AssemblyName(string assemblyName) { }
+		public string CodeBase { get { throw null; } set { } }
+		public System.Reflection.AssemblyContentType ContentType { get { throw null; } set { } }
+		public System.Globalization.CultureInfo CultureInfo { get { throw null; } set { } }
+		public string CultureName { get { throw null; } set { } }
+		public string EscapedCodeBase { get { throw null; } }
+		public System.Reflection.AssemblyNameFlags Flags { get { throw null; } set { } }
+		public string FullName { get { throw null; } }
+		public System.Configuration.Assemblies.AssemblyHashAlgorithm HashAlgorithm { get { throw null; } set { } }
+		public System.Reflection.StrongNameKeyPair KeyPair { get { throw null; } set { } }
+		public string Name { get { throw null; } set { } }
+		public System.Reflection.ProcessorArchitecture ProcessorArchitecture { get { throw null; } set { } }
+		public System.Version Version { get { throw null; } set { } }
+		public System.Configuration.Assemblies.AssemblyVersionCompatibility VersionCompatibility { get { throw null; } set { } }
+		public object Clone() { throw null; }
+		public static System.Reflection.AssemblyName GetAssemblyName(string assemblyFile) { throw null; }
+		public void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
+		public byte[] GetPublicKey() { throw null; }
+		public byte[] GetPublicKeyToken() { throw null; }
+		public void OnDeserialization(object sender) { }
+		public static bool ReferenceMatchesDefinition(System.Reflection.AssemblyName reference, System.Reflection.AssemblyName definition) { throw null; }
+		public void SetPublicKey(byte[] publicKey) { }
+		public void SetPublicKeyToken(byte[] publicKeyToken) { }
+		public override string ToString() { throw null; }
+
+		internal static string EscapeCodeBase (string codebase) { throw null; }
+	}
+}

+ 44 - 0
mcs/class/System.Private.CoreLib/System.Reflection/CustomAttributeExtensions.cs

@@ -0,0 +1,44 @@
+using System.Collections.Generic;
+
+namespace System.Reflection
+{
+	public static class CustomAttributeExtensions
+	{
+		public static System.Attribute GetCustomAttribute(this System.Reflection.Assembly element, System.Type attributeType) { throw null; }
+		public static System.Attribute GetCustomAttribute(this System.Reflection.MemberInfo element, System.Type attributeType) { throw null; }
+		public static System.Attribute GetCustomAttribute(this System.Reflection.MemberInfo element, System.Type attributeType, bool inherit) { throw null; }
+		public static System.Attribute GetCustomAttribute(this System.Reflection.Module element, System.Type attributeType) { throw null; }
+		public static System.Attribute GetCustomAttribute(this System.Reflection.ParameterInfo element, System.Type attributeType) { throw null; }
+		public static System.Attribute GetCustomAttribute(this System.Reflection.ParameterInfo element, System.Type attributeType, bool inherit) { throw null; }
+		public static System.Collections.Generic.IEnumerable<System.Attribute> GetCustomAttributes(this System.Reflection.Assembly element) { throw null; }
+		public static System.Collections.Generic.IEnumerable<System.Attribute> GetCustomAttributes(this System.Reflection.Assembly element, System.Type attributeType) { throw null; }
+		public static System.Collections.Generic.IEnumerable<System.Attribute> GetCustomAttributes(this System.Reflection.MemberInfo element) { throw null; }
+		public static System.Collections.Generic.IEnumerable<System.Attribute> GetCustomAttributes(this System.Reflection.MemberInfo element, bool inherit) { throw null; }
+		public static System.Collections.Generic.IEnumerable<System.Attribute> GetCustomAttributes(this System.Reflection.MemberInfo element, System.Type attributeType) { throw null; }
+		public static System.Collections.Generic.IEnumerable<System.Attribute> GetCustomAttributes(this System.Reflection.MemberInfo element, System.Type attributeType, bool inherit) { throw null; }
+		public static System.Collections.Generic.IEnumerable<System.Attribute> GetCustomAttributes(this System.Reflection.Module element) { throw null; }
+		public static System.Collections.Generic.IEnumerable<System.Attribute> GetCustomAttributes(this System.Reflection.Module element, System.Type attributeType) { throw null; }
+		public static System.Collections.Generic.IEnumerable<System.Attribute> GetCustomAttributes(this System.Reflection.ParameterInfo element) { throw null; }
+		public static System.Collections.Generic.IEnumerable<System.Attribute> GetCustomAttributes(this System.Reflection.ParameterInfo element, bool inherit) { throw null; }
+		public static System.Collections.Generic.IEnumerable<System.Attribute> GetCustomAttributes(this System.Reflection.ParameterInfo element, System.Type attributeType) { throw null; }
+		public static System.Collections.Generic.IEnumerable<System.Attribute> GetCustomAttributes(this System.Reflection.ParameterInfo element, System.Type attributeType, bool inherit) { throw null; }
+		public static System.Collections.Generic.IEnumerable<T> GetCustomAttributes<T>(this System.Reflection.Assembly element) where T : System.Attribute { throw null; }
+		public static System.Collections.Generic.IEnumerable<T> GetCustomAttributes<T>(this System.Reflection.MemberInfo element) where T : System.Attribute { throw null; }
+		public static System.Collections.Generic.IEnumerable<T> GetCustomAttributes<T>(this System.Reflection.MemberInfo element, bool inherit) where T : System.Attribute { throw null; }
+		public static System.Collections.Generic.IEnumerable<T> GetCustomAttributes<T>(this System.Reflection.Module element) where T : System.Attribute { throw null; }
+		public static System.Collections.Generic.IEnumerable<T> GetCustomAttributes<T>(this System.Reflection.ParameterInfo element) where T : System.Attribute { throw null; }
+		public static System.Collections.Generic.IEnumerable<T> GetCustomAttributes<T>(this System.Reflection.ParameterInfo element, bool inherit) where T : System.Attribute { throw null; }
+		public static T GetCustomAttribute<T>(this System.Reflection.Assembly element) where T : System.Attribute { throw null; }
+		public static T GetCustomAttribute<T>(this System.Reflection.MemberInfo element) where T : System.Attribute { throw null; }
+		public static T GetCustomAttribute<T>(this System.Reflection.MemberInfo element, bool inherit) where T : System.Attribute { throw null; }
+		public static T GetCustomAttribute<T>(this System.Reflection.Module element) where T : System.Attribute { throw null; }
+		public static T GetCustomAttribute<T>(this System.Reflection.ParameterInfo element) where T : System.Attribute { throw null; }
+		public static T GetCustomAttribute<T>(this System.Reflection.ParameterInfo element, bool inherit) where T : System.Attribute { throw null; }
+		public static bool IsDefined(this System.Reflection.Assembly element, System.Type attributeType) { throw null; }
+		public static bool IsDefined(this System.Reflection.MemberInfo element, System.Type attributeType) { throw null; }
+		public static bool IsDefined(this System.Reflection.MemberInfo element, System.Type attributeType, bool inherit) { throw null; }
+		public static bool IsDefined(this System.Reflection.Module element, System.Type attributeType) { throw null; }
+		public static bool IsDefined(this System.Reflection.ParameterInfo element, System.Type attributeType) { throw null; }
+		public static bool IsDefined(this System.Reflection.ParameterInfo element, System.Type attributeType, bool inherit) { throw null; }
+	}
+}

+ 8 - 0
mcs/class/System.Private.CoreLib/System.Reflection/FieldInfo.cs

@@ -0,0 +1,8 @@
+namespace System.Reflection
+{
+	partial class FieldInfo
+	{
+		public static FieldInfo GetFieldFromHandle (RuntimeFieldHandle handle) { throw null; }
+		public static FieldInfo GetFieldFromHandle (RuntimeFieldHandle handle, RuntimeTypeHandle declaringType) { throw null; }		
+	}
+}

+ 30 - 0
mcs/class/System.Private.CoreLib/System.Reflection/MethodBase.cs

@@ -0,0 +1,30 @@
+namespace System.Reflection
+{
+	partial class MethodBase
+	{
+		public static MethodBase GetMethodFromHandle (RuntimeMethodHandle handle) { throw null; }
+		public static MethodBase GetMethodFromHandle (RuntimeMethodHandle handle, RuntimeTypeHandle declaringType) { throw null; }
+
+		public static MethodBase GetCurrentMethod() { throw null; }
+
+		internal virtual ParameterInfo[] GetParametersNoCopy ()
+		{
+			throw new NotImplementedException ();
+		}
+
+		internal virtual ParameterInfo[] GetParametersInternal ()
+		{
+			throw new NotImplementedException ();
+		}
+
+		internal virtual int GetParametersCount ()
+		{
+			throw new NotImplementedException ();
+		}
+
+		internal static MethodBase GetMethodFromHandleNoGenericCheck (RuntimeMethodHandle handle)
+		{
+			throw new NotImplementedException ();
+		}
+	}
+}

+ 37 - 0
mcs/class/System.Private.CoreLib/System.Resources/ResourceManager.cs

@@ -0,0 +1,37 @@
+using System.Reflection;
+using System.Globalization;
+
+namespace System.Resources
+{
+	public class ResourceManager
+	{
+		public static readonly int HeaderVersionNumber;
+		public static readonly int MagicNumber;
+		protected System.Reflection.Assembly MainAssembly;
+		protected ResourceManager() { }
+		public ResourceManager(string baseName, System.Reflection.Assembly assembly) { }
+		public ResourceManager(string baseName, System.Reflection.Assembly assembly, System.Type usingResourceSet) { }
+		public ResourceManager(System.Type resourceSource) { }
+		public virtual string BaseName { get { throw null; } }
+		public virtual bool IgnoreCase { get { throw null; } set { } }
+		public virtual System.Type ResourceSetType { get { throw null; } }
+		protected static System.Globalization.CultureInfo GetNeutralResourcesLanguage(System.Reflection.Assembly a) { throw null; }
+		public virtual object GetObject(string name) { throw null; }
+		public virtual object GetObject(string name, System.Globalization.CultureInfo culture) { throw null; }
+		protected virtual string GetResourceFileName(System.Globalization.CultureInfo culture) { throw null; }
+		public virtual ResourceSet GetResourceSet(System.Globalization.CultureInfo culture, bool createIfNotExists, bool tryParents) { throw null; }
+		protected static System.Version GetSatelliteContractVersion(System.Reflection.Assembly a) { throw null; }
+		public System.IO.UnmanagedMemoryStream GetStream(string name) { throw null; }
+		public System.IO.UnmanagedMemoryStream GetStream(string name, System.Globalization.CultureInfo culture) { throw null; }
+		public virtual string GetString(string name) { throw null; }
+		public virtual string GetString(string name, System.Globalization.CultureInfo culture) { throw null; }
+		protected virtual ResourceSet InternalGetResourceSet(System.Globalization.CultureInfo culture, bool createIfNotExists, bool tryParents) { throw null; }
+		public virtual void ReleaseAllResources() { }
+		protected UltimateResourceFallbackLocation FallbackLocation { get { throw null; } set { } }
+		public static ResourceManager CreateFileBasedResourceManager(string baseName, string resourceDir, System.Type usingResourceSet) { throw null; }
+
+
+		internal static bool IsDefaultType(string asmTypeName, string typeName) { throw null; }
+		internal const string ResReaderTypeName = "System.Resources.ResourceReader";
+	}
+}

+ 8 - 0
mcs/class/System.Private.CoreLib/System.Runtime.CompilerServices/RuntimeFeature.cs

@@ -0,0 +1,8 @@
+namespace System.Runtime.CompilerServices
+{
+	partial class RuntimeFeature
+	{
+		public static bool IsDynamicCodeSupported => true;
+		public static bool IsDynamicCodeCompiled => true;
+	}
+}

+ 15 - 0
mcs/class/System.Private.CoreLib/System.Runtime.CompilerServices/RuntimeHelpers.cs

@@ -0,0 +1,15 @@
+namespace System.Runtime.CompilerServices
+{
+	partial class RuntimeHelpers
+	{
+		internal static unsafe bool ObjectHasComponentSize (object obj)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public static object GetUninitializedObject (Type type)
+		{
+			throw new NotImplementedException ();
+		}
+	}
+}

+ 9 - 0
mcs/class/System.Private.CoreLib/System.Runtime.InteropServices/ComEventsHelper.cs

@@ -0,0 +1,9 @@
+namespace System.Runtime.InteropServices
+{
+	public static class ComEventsHelper
+	{
+		public static void Combine (object rcw, Guid iid, int dispid, System.Delegate d) => throw new PlatformNotSupportedException ();
+
+		public static Delegate Remove (object rcw, Guid iid, int dispid, System.Delegate d) => throw new PlatformNotSupportedException ();
+	}
+}

+ 9 - 0
mcs/class/System.Private.CoreLib/System.Runtime.InteropServices/CriticalHandle.cs

@@ -0,0 +1,9 @@
+namespace System.Runtime.InteropServices
+{
+	partial class CriticalHandle
+	{
+		void ReleaseHandleFailed ()
+		{
+		}
+	}
+}

+ 15 - 0
mcs/class/System.Private.CoreLib/System.Runtime.InteropServices/InteropExtensions.cs

@@ -0,0 +1,15 @@
+namespace System.Runtime.InteropServices
+{
+	public static class InteropExtensions
+	{
+		public static bool IsBlittable (this object obj)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public static int GetElementSize (this Array array)
+		{
+			throw new NotImplementedException ();
+		}
+	}
+}

+ 253 - 0
mcs/class/System.Private.CoreLib/System.Runtime.InteropServices/Marshal.cs

@@ -0,0 +1,253 @@
+using System.Runtime.InteropServices.ComTypes;
+
+namespace System.Runtime.InteropServices
+{
+	public static partial class Marshal
+	{
+		public static readonly int SystemDefaultCharSize;
+		public static readonly int SystemMaxDBCSCharSize;
+		public static int AddRef(System.IntPtr pUnk) { throw null; }
+		public static System.IntPtr AllocCoTaskMem(int cb) { throw null; }
+		public static System.IntPtr AllocHGlobal(int cb) { throw null; }
+		public static System.IntPtr AllocHGlobal(System.IntPtr cb) { throw null; }
+		public static bool AreComObjectsAvailableForCleanup() { throw null; }
+		public static object BindToMoniker(string monikerName) { throw null; }
+		public static void ChangeWrapperHandleStrength(object otp, bool fIsWeak) { }        
+		public static void CleanupUnusedObjectsInCurrentContext() { }
+		public static void Copy(byte[] source, int startIndex, System.IntPtr destination, int length) { }
+		public static void Copy(char[] source, int startIndex, System.IntPtr destination, int length) { }
+		public static void Copy(double[] source, int startIndex, System.IntPtr destination, int length) { }
+		public static void Copy(short[] source, int startIndex, System.IntPtr destination, int length) { }
+		public static void Copy(int[] source, int startIndex, System.IntPtr destination, int length) { }
+		public static void Copy(long[] source, int startIndex, System.IntPtr destination, int length) { }
+		public static void Copy(System.IntPtr source, byte[] destination, int startIndex, int length) { }
+		public static void Copy(System.IntPtr source, char[] destination, int startIndex, int length) { }
+		public static void Copy(System.IntPtr source, double[] destination, int startIndex, int length) { }
+		public static void Copy(System.IntPtr source, short[] destination, int startIndex, int length) { }
+		public static void Copy(System.IntPtr source, int[] destination, int startIndex, int length) { }
+		public static void Copy(System.IntPtr source, long[] destination, int startIndex, int length) { }
+		public static void Copy(System.IntPtr source, System.IntPtr[] destination, int startIndex, int length) { }
+		public static void Copy(System.IntPtr source, float[] destination, int startIndex, int length) { }
+		public static void Copy(System.IntPtr[] source, int startIndex, System.IntPtr destination, int length) { }
+		public static void Copy(float[] source, int startIndex, System.IntPtr destination, int length) { }
+		[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
+		public static System.IntPtr CreateAggregatedObject(System.IntPtr pOuter, object o) { throw null; }
+		public static System.IntPtr CreateAggregatedObject<T>(System.IntPtr pOuter, T o) { throw null; }
+		[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
+		public static object CreateWrapperOfType(object o, System.Type t) { throw null; }
+		public static TWrapper CreateWrapperOfType<T, TWrapper>(T o) { throw null; }
+		[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
+		public static void DestroyStructure(System.IntPtr ptr, System.Type structuretype) { }
+		public static void DestroyStructure<T>(System.IntPtr ptr) { }
+		public static int FinalReleaseComObject(object o) { throw null; }
+		public static void FreeBSTR(System.IntPtr ptr) { }
+		public static void FreeCoTaskMem(System.IntPtr ptr) { }
+		public static void FreeHGlobal(System.IntPtr hglobal) { }
+		public static Guid GenerateGuidForType(System.Type type) { throw null; }
+		public static string GenerateProgIdForType(System.Type type) { throw null; }
+		[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
+		public static System.IntPtr GetComInterfaceForObject(object o, System.Type T) { throw null; }
+		[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
+//        public static System.IntPtr GetComInterfaceForObject(object o, System.Type T, System.Runtime.InteropServices.CustomQueryInterfaceMode mode) { throw null; }
+		public static System.IntPtr GetComInterfaceForObject<T, TInterface>(T o) { throw null; }
+		public static object GetComObjectData(object obj, object key) { throw null; }              
+		[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
+		public static System.Delegate GetDelegateForFunctionPointer(System.IntPtr ptr, System.Type t) { throw null; }
+		public static TDelegate GetDelegateForFunctionPointer<TDelegate>(System.IntPtr ptr) { throw null; }
+		[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
+		[System.ObsoleteAttribute("GetExceptionCode() may be unavailable in future releases.")]
+		public static int GetExceptionCode() { throw null; }
+		public static System.Exception GetExceptionForHR(int errorCode) { throw null; }
+		public static System.Exception GetExceptionForHR(int errorCode, System.IntPtr errorInfo) { throw null; }
+		public static IntPtr GetExceptionPointers() { throw null; }
+		[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
+		public static System.IntPtr GetFunctionPointerForDelegate(System.Delegate d) { throw null; }
+		public static System.IntPtr GetFunctionPointerForDelegate<TDelegate>(TDelegate d) { throw null; }
+		public static System.IntPtr GetHINSTANCE(System.Reflection.Module m) { throw null; }
+		public static int GetHRForException(System.Exception e) { throw null; }
+		public static int GetHRForLastWin32Error() { throw null; }
+		public static System.IntPtr GetIDispatchForObject(object o) { throw null; }
+		public static System.IntPtr GetIUnknownForObject(object o) { throw null; }
+		public static int GetLastWin32Error() { throw null; }
+		[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
+		[System.ObsoleteAttribute("GetNativeVariantForObject(Object, IntPtr) may be unavailable in future releases.")]
+		public static void GetNativeVariantForObject(object obj, System.IntPtr pDstNativeVariant) { }
+		[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
+		[System.ObsoleteAttribute("GetNativeVariantForObject<T>(T, IntPtr) may be unavailable in future releases.")]
+		public static void GetNativeVariantForObject<T>(T obj, System.IntPtr pDstNativeVariant) { }
+		public static object GetObjectForIUnknown(System.IntPtr pUnk) { throw null; }
+		[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
+		[System.ObsoleteAttribute("GetObjectForNativeVariant(IntPtr) may be unavailable in future releases.")]
+		public static object GetObjectForNativeVariant(System.IntPtr pSrcNativeVariant) { throw null; }
+		[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
+		[System.ObsoleteAttribute("GetObjectForNativeVariant<T>(IntPtr) may be unavailable in future releases.")]
+		public static T GetObjectForNativeVariant<T>(System.IntPtr pSrcNativeVariant) { throw null; }
+		[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
+		[System.ObsoleteAttribute("GetObjectsForNativeVariants(IntPtr, Int32) may be unavailable in future releases.")]
+		public static object[] GetObjectsForNativeVariants(System.IntPtr aSrcNativeVariant, int cVars) { throw null; }
+		[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
+		[System.ObsoleteAttribute("GetObjectsForNativeVariants<T>(IntPtr, Int32) may be unavailable in future releases.")]
+		public static T[] GetObjectsForNativeVariants<T>(System.IntPtr aSrcNativeVariant, int cVars) { throw null; }
+		public static int GetStartComSlot(System.Type t) { throw null; }
+		public static int GetEndComSlot(System.Type t) { throw null; }
+		public static object GetTypedObjectForIUnknown(System.IntPtr pUnk, System.Type t) { throw null; }
+		public static System.Type GetTypeFromCLSID(System.Guid clsid) { throw null; }
+//        public static string GetTypeInfoName(System.Runtime.InteropServices.ComTypes.ITypeInfo typeInfo) { throw null; }
+		public static object GetUniqueObjectForIUnknown(System.IntPtr unknown) { throw null; }
+		public static bool IsComObject(object o) { throw null; }
+		[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
+		public static System.IntPtr OffsetOf(System.Type t, string fieldName) { throw null; }
+		public static System.IntPtr OffsetOf<T>(string fieldName) { throw null; }
+		public static void Prelink(System.Reflection.MethodInfo m) { }
+		public static void PrelinkAll(Type c) { }
+		public static string PtrToStringAuto(System.IntPtr ptr) { throw null; }
+		public static string PtrToStringAuto(System.IntPtr ptr, int len) { throw null; }        
+		public static string PtrToStringAnsi(System.IntPtr ptr) { throw null; }
+		public static string PtrToStringAnsi(System.IntPtr ptr, int len) { throw null; }
+		public static string PtrToStringBSTR(System.IntPtr ptr) { throw null; }
+		public static string PtrToStringUni(System.IntPtr ptr) { throw null; }
+		public static string PtrToStringUni(System.IntPtr ptr, int len) { throw null; }
+		public static string PtrToStringUTF8(System.IntPtr ptr) { throw null; }
+		public static string PtrToStringUTF8(System.IntPtr ptr, int byteLen) { throw null; }
+		[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
+		public static void PtrToStructure(System.IntPtr ptr, object structure) { }
+		[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
+		public static object PtrToStructure(System.IntPtr ptr, System.Type structureType) { throw null; }
+		public static T PtrToStructure<T>(System.IntPtr ptr) { throw null; }
+		public static void PtrToStructure<T>(System.IntPtr ptr, T structure) { }
+		public static bool IsTypeVisibleFromCom(Type t) { throw null;}
+		public static int QueryInterface(System.IntPtr pUnk, ref System.Guid iid, out System.IntPtr ppv) { throw null; }
+		public static byte ReadByte(System.IntPtr ptr) { throw null; }
+		public static byte ReadByte(System.IntPtr ptr, int ofs) { throw null; }
+		[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
+		[System.ObsoleteAttribute("ReadByte(Object, Int32) may be unavailable in future releases.")]
+		public static byte ReadByte(object ptr, int ofs) { throw null; }
+		public static short ReadInt16(System.IntPtr ptr) { throw null; }
+		public static short ReadInt16(System.IntPtr ptr, int ofs) { throw null; }
+		[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
+		[System.ObsoleteAttribute("ReadInt16(Object, Int32) may be unavailable in future releases.")]
+		public static short ReadInt16(object ptr, int ofs) { throw null; }
+		public static int ReadInt32(System.IntPtr ptr) { throw null; }
+		public static int ReadInt32(System.IntPtr ptr, int ofs) { throw null; }
+		[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
+		[System.ObsoleteAttribute("ReadInt32(Object, Int32) may be unavailable in future releases.")]
+		public static int ReadInt32(object ptr, int ofs) { throw null; }
+		public static long ReadInt64(System.IntPtr ptr) { throw null; }
+		public static long ReadInt64(System.IntPtr ptr, int ofs) { throw null; }
+		[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
+		[System.ObsoleteAttribute("ReadInt64(Object, Int32) may be unavailable in future releases.")]
+		public static long ReadInt64(object ptr, int ofs) { throw null; }
+		public static System.IntPtr ReadIntPtr(System.IntPtr ptr) { throw null; }
+		public static System.IntPtr ReadIntPtr(System.IntPtr ptr, int ofs) { throw null; }
+		[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
+		[System.ObsoleteAttribute("ReadIntPtr(Object, Int32) may be unavailable in future releases.")]
+		public static System.IntPtr ReadIntPtr(object ptr, int ofs) { throw null; }
+		public static System.IntPtr ReAllocCoTaskMem(System.IntPtr pv, int cb) { throw null; }
+		public static System.IntPtr ReAllocHGlobal(System.IntPtr pv, System.IntPtr cb) { throw null; }
+		public static int Release(System.IntPtr pUnk) { throw null; }
+		public static int ReleaseComObject(object o) { throw null; }
+		[System.CLSCompliant(false)]
+		public static IntPtr SecureStringToBSTR(System.Security.SecureString s) { throw null; }
+		[System.CLSCompliant(false)]
+		public static IntPtr SecureStringToCoTaskMemAnsi(System.Security.SecureString s) { throw null; }
+		[System.CLSCompliant(false)]
+		public static IntPtr SecureStringToCoTaskMemUnicode(System.Security.SecureString s) { throw null; }
+		[System.CLSCompliant(false)]
+		public static IntPtr SecureStringToGlobalAllocAnsi(System.Security.SecureString s) { throw null; }
+		[System.CLSCompliant(false)]
+		public static IntPtr SecureStringToGlobalAllocUnicode(System.Security.SecureString s) { throw null; }
+		public static bool SetComObjectData(object obj, object key, object data) { throw null; }
+		[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
+		public static int SizeOf(object structure) { throw null; }
+		[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
+		public static int SizeOf(System.Type t) { throw null; }
+		public static int SizeOf<T>() { throw null; }
+		public static int SizeOf<T>(T structure) { throw null; }
+		public static System.IntPtr StringToBSTR(string s) { throw null; }
+		public static System.IntPtr StringToCoTaskMemAnsi(string s) { throw null; }
+		public static System.IntPtr StringToCoTaskMemAuto(string s) { throw null; }
+		public static System.IntPtr StringToCoTaskMemUni(string s) { throw null; }
+		public static System.IntPtr StringToCoTaskMemUTF8(string s) { throw null; }
+		public static System.IntPtr StringToHGlobalAnsi(string s) { throw null; }
+		public static System.IntPtr StringToHGlobalAuto(string s) { throw null; }
+		public static System.IntPtr StringToHGlobalUni(string s) { throw null; }
+		[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
+		public static void StructureToPtr(object structure, System.IntPtr ptr, bool fDeleteOld) { }
+		public static void StructureToPtr<T>(T structure, System.IntPtr ptr, bool fDeleteOld) { }
+		public static void ThrowExceptionForHR(int errorCode) { }
+		public static void ThrowExceptionForHR(int errorCode, System.IntPtr errorInfo) { }
+		[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
+		public static System.IntPtr UnsafeAddrOfPinnedArrayElement(System.Array arr, int index) { throw null; }
+		public static System.IntPtr UnsafeAddrOfPinnedArrayElement<T>(T[] arr, int index) { throw null; }
+		public static void WriteByte(System.IntPtr ptr, byte val) { }
+		public static void WriteByte(System.IntPtr ptr, int ofs, byte val) { }
+		[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
+		[System.ObsoleteAttribute("WriteByte(Object, Int32, Byte) may be unavailable in future releases.")]
+		public static void WriteByte(object ptr, int ofs, byte val) { throw null; }
+		public static void WriteInt16(System.IntPtr ptr, char val) { }
+		public static void WriteInt16(System.IntPtr ptr, short val) { }
+		public static void WriteInt16(System.IntPtr ptr, int ofs, char val) { }
+		public static void WriteInt16(System.IntPtr ptr, int ofs, short val) { }
+		[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
+		[System.ObsoleteAttribute("WriteInt16(Object, Int32, Char) may be unavailable in future releases.")]
+		public static void WriteInt16(object ptr, int ofs, char val) { throw null; }
+		[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
+		[System.ObsoleteAttribute("WriteInt16(Object, Int32, Int16) may be unavailable in future releases.")]
+		public static void WriteInt16(object ptr, int ofs, short val) { throw null; }
+		public static void WriteInt32(System.IntPtr ptr, int val) { }
+		public static void WriteInt32(System.IntPtr ptr, int ofs, int val) { }
+		[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
+		[System.ObsoleteAttribute("WriteInt32(Object, Int32, Int32) may be unavailable in future releases.")]
+		public static void WriteInt32(object ptr, int ofs, int val) { throw null; }
+		public static void WriteInt64(System.IntPtr ptr, int ofs, long val) { }
+		public static void WriteInt64(System.IntPtr ptr, long val) { }
+		[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
+		[System.ObsoleteAttribute("WriteInt64(Object, Int32, Int64) may be unavailable in future releases.")]
+		public static void WriteInt64(object ptr, int ofs, long val) { throw null; }
+		public static void WriteIntPtr(System.IntPtr ptr, int ofs, System.IntPtr val) { }
+		public static void WriteIntPtr(System.IntPtr ptr, System.IntPtr val) { }
+		[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
+		[System.ObsoleteAttribute("WriteIntPtr(Object, Int32, IntPtr) may be unavailable in future releases.")]
+		public static void WriteIntPtr(object ptr, int ofs, System.IntPtr val) { throw null; }
+		public static void ZeroFreeBSTR(System.IntPtr s) { }
+		public static void ZeroFreeCoTaskMemAnsi(System.IntPtr s) { }
+		public static void ZeroFreeCoTaskMemUnicode(System.IntPtr s) { }
+		public static void ZeroFreeGlobalAllocAnsi(System.IntPtr s) { }
+		public static void ZeroFreeGlobalAllocUnicode(System.IntPtr s) { }
+		public static void ZeroFreeCoTaskMemUTF8(System.IntPtr s) { }
+
+
+		internal static void SetLastWin32Error (int error)
+		{
+		}
+
+		internal static IntPtr AllocBSTR (int length)
+		{
+			throw new NotImplementedException ();
+		}
+	}
+
+	partial class Marshal
+	{
+		public static void FreeLibrary(System.IntPtr handle) { }
+		public static System.IntPtr GetLibraryExport(System.IntPtr handle, string name) { throw null; }
+		public static System.IntPtr LoadLibrary(string libraryPath) { throw null; }
+		public static System.IntPtr LoadLibrary(string libraryName, System.Reflection.Assembly assembly, DllImportSearchPath? searchPath) { throw null; }
+		public static bool TryGetLibraryExport(System.IntPtr handle, string name, out System.IntPtr address) { throw null; }
+		public static bool TryLoadLibrary(string libraryPath, out System.IntPtr handle) { throw null; }
+		public static bool TryLoadLibrary(string libraryName, System.Reflection.Assembly assembly, DllImportSearchPath? searchPath, out System.IntPtr handle) { throw null; }
+	}
+
+	partial class Marshal
+	{
+		public static IntPtr GetComInterfaceForObject(object o, Type T, CustomQueryInterfaceMode mode)
+		{
+			throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
+		}
+
+		public static string GetTypeInfoName(ITypeInfo typeInfo)
+		{
+			throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
+		}
+	}
+}

+ 38 - 0
mcs/class/System.Private.CoreLib/System.Runtime.Loader/AssemblyLoadContext.cs

@@ -0,0 +1,38 @@
+using System.Reflection;
+
+namespace System.Runtime.Loader
+{
+	public abstract class AssemblyLoadContext
+	{
+		protected AssemblyLoadContext() { }
+		protected AssemblyLoadContext(bool isCollectible) { }
+		public bool IsCollectible { get { throw null; } }
+		public void Unload() { throw null; }
+		public static System.Runtime.Loader.AssemblyLoadContext Default { get { throw null; } }
+		public static System.Reflection.AssemblyName GetAssemblyName(string assemblyPath) { throw null; }
+		public static System.Runtime.Loader.AssemblyLoadContext GetLoadContext(System.Reflection.Assembly assembly) { throw null; }
+		protected abstract System.Reflection.Assembly Load(System.Reflection.AssemblyName assemblyName);
+		public System.Reflection.Assembly LoadFromAssemblyName(System.Reflection.AssemblyName assemblyName) { throw null; }
+		public System.Reflection.Assembly LoadFromAssemblyPath(string assemblyPath) { throw null; }
+		public System.Reflection.Assembly LoadFromNativeImagePath(string nativeImagePath, string assemblyPath) { throw null; }
+		public System.Reflection.Assembly LoadFromStream(System.IO.Stream assembly) { throw null; }
+		public System.Reflection.Assembly LoadFromStream(System.IO.Stream assembly, System.IO.Stream assemblySymbols) { throw null; }
+		protected System.IntPtr LoadUnmanagedDllFromPath(string unmanagedDllPath) { throw null; }
+		protected virtual System.IntPtr LoadUnmanagedDll(string unmanagedDllName) { throw null; }
+		public void SetProfileOptimizationRoot(string directoryPath) { }
+		public void StartProfileOptimization(string profile) { }
+		public event Func<AssemblyLoadContext, System.Reflection.AssemblyName, System.Reflection.Assembly> Resolving;
+		public event Action<AssemblyLoadContext> Unloading;
+		
+		internal static void OnProcessExit ()
+		{
+		}
+
+		public static Assembly[] GetLoadedAssemblies() => throw new NotImplementedException();
+
+		public static event AssemblyLoadEventHandler AssemblyLoad;
+		public static event ResolveEventHandler TypeResolve;
+		public static event ResolveEventHandler ResourceResolve;
+		public static event ResolveEventHandler AssemblyResolve;
+	}
+}

+ 13 - 0
mcs/class/System.Private.CoreLib/System.Threading/EventWaitHandle.cs

@@ -0,0 +1,13 @@
+namespace System.Threading
+{
+	partial class EventWaitHandle
+	{
+		public bool Set () => throw new NotImplementedException ();
+
+		public bool Reset () => throw new NotImplementedException ();
+
+		private void CreateEventCore (bool initialState, EventResetMode mode, string name, out bool createdNew) => throw new NotImplementedException ();
+
+		private static OpenExistingResult OpenExistingWorker(string name, out EventWaitHandle result) => throw new NotImplementedException ();
+	}
+}

+ 10 - 0
mcs/class/System.Private.CoreLib/System.Threading/Interlocked.cs

@@ -0,0 +1,10 @@
+namespace System.Threading
+{
+	partial class Interlocked
+	{
+		public static void MemoryBarrierProcessWide ()
+		{
+			throw new NotImplementedException ();
+		}
+	}
+}

+ 14 - 0
mcs/class/System.Private.CoreLib/System.Threading/Mutex.cs

@@ -0,0 +1,14 @@
+namespace System.Threading
+{
+	partial class Mutex
+	{
+		void CreateMutexCore (bool initiallyOwned, string name, out bool createdNew) => throw new NotImplementedException ();
+
+		static OpenExistingResult OpenExistingWorker (string name, out Mutex result) => throw new NotImplementedException ();
+
+		public void ReleaseMutex ()
+		{
+			throw new NotImplementedException ();
+		}
+	}
+}

+ 30 - 0
mcs/class/System.Private.CoreLib/System.Threading/Overlapped.cs

@@ -0,0 +1,30 @@
+namespace System.Threading
+{
+	public class Overlapped
+	{
+		public Overlapped() { }
+		[System.ObsoleteAttribute("This constructor is not 64-bit compatible.  Use the constructor that takes an IntPtr for the event handle.  https://go.microsoft.com/fwlink/?linkid=14202")]
+		public Overlapped(int offsetLo, int offsetHi, int hEvent, System.IAsyncResult ar) { }
+		public Overlapped(int offsetLo, int offsetHi, System.IntPtr hEvent, System.IAsyncResult ar) { }
+		public System.IAsyncResult AsyncResult { get { throw null; } set { } }
+		[System.ObsoleteAttribute("This property is not 64-bit compatible.  Use EventHandleIntPtr instead.  https://go.microsoft.com/fwlink/?linkid=14202")]
+		public int EventHandle { get { throw null; } set { } }
+		public System.IntPtr EventHandleIntPtr { get { throw null; } set { } }
+		public int OffsetHigh { get { throw null; } set { } }
+		public int OffsetLow { get { throw null; } set { } }
+		[System.CLSCompliantAttribute(false)]
+		public static unsafe void Free(System.Threading.NativeOverlapped* nativeOverlappedPtr) { }
+		[System.CLSCompliantAttribute(false)]
+		[System.ObsoleteAttribute("This method is not safe.  Use Pack (iocb, userData) instead.  https://go.microsoft.com/fwlink/?linkid=14202")]
+		public unsafe System.Threading.NativeOverlapped* Pack(System.Threading.IOCompletionCallback iocb) { throw null; }
+		[System.CLSCompliantAttribute(false)]
+		public unsafe System.Threading.NativeOverlapped* Pack(System.Threading.IOCompletionCallback iocb, object userData) { throw null; }
+		[System.CLSCompliantAttribute(false)]
+		public static unsafe System.Threading.Overlapped Unpack(System.Threading.NativeOverlapped* nativeOverlappedPtr) { throw null; }
+		[System.CLSCompliantAttribute(false)]
+		[System.ObsoleteAttribute("This method is not safe.  Use UnsafePack (iocb, userData) instead.  https://go.microsoft.com/fwlink/?linkid=14202")]
+		public unsafe System.Threading.NativeOverlapped* UnsafePack(System.Threading.IOCompletionCallback iocb) { throw null; }
+		[System.CLSCompliantAttribute(false)]
+		public unsafe System.Threading.NativeOverlapped* UnsafePack(System.Threading.IOCompletionCallback iocb, object userData) { throw null; }
+	}
+}

+ 9 - 0
mcs/class/System.Private.CoreLib/System.Threading/PreAllocatedOverlapped.cs

@@ -0,0 +1,9 @@
+namespace System.Threading
+{
+	public sealed class PreAllocatedOverlapped : System.IDisposable
+	{
+		[System.CLSCompliantAttribute(false)]
+		public PreAllocatedOverlapped(System.Threading.IOCompletionCallback callback, object state, object pinData) { }
+		public void Dispose() { }
+	}
+}

+ 11 - 0
mcs/class/System.Private.CoreLib/System.Threading/Semaphore.cs

@@ -0,0 +1,11 @@
+namespace System.Threading
+{
+    partial class Semaphore
+    {
+		int ReleaseCore (int releaseCount) => throw new NotImplementedException ();
+
+		static OpenExistingResult OpenExistingWorker(string name, out Semaphore result) => throw new NotImplementedException ();
+
+		void CreateSemaphoreCore(int initialCount, int maximumCount, string name, out bool createdNew) => throw new NotImplementedException ();
+    }
+}

+ 19 - 0
mcs/class/System.Private.CoreLib/System.Threading/SynchronizationContext.cs

@@ -0,0 +1,19 @@
+namespace System.Threading
+{
+	public partial class SynchronizationContext
+	{
+		public static System.Threading.SynchronizationContext Current { get { throw null; } }
+		public virtual System.Threading.SynchronizationContext CreateCopy() { throw null; }
+		public bool IsWaitNotificationRequired() { throw null; }
+		public virtual void OperationCompleted() { }
+		public virtual void OperationStarted() { }
+		public virtual void Post(System.Threading.SendOrPostCallback d, object state) { }
+		public virtual void Send(System.Threading.SendOrPostCallback d, object state) { }
+		public static void SetSynchronizationContext(System.Threading.SynchronizationContext syncContext) { }
+		protected void SetWaitNotificationRequired() { }
+		[System.CLSCompliantAttribute(false)]
+		public virtual int Wait(System.IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout) { throw null; }
+		[System.CLSCompliantAttribute(false)]
+		protected static int WaitHelper(System.IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout) { throw null; }
+	}
+}

+ 21 - 0
mcs/class/System.Private.CoreLib/System.Threading/Thread.cs

@@ -0,0 +1,21 @@
+namespace System.Threading
+{
+	partial class Thread
+	{
+		public ExecutionContext ExecutionContext {
+			get {
+				throw new NotImplementedException ();
+			}
+			set {
+			}
+		}
+
+		public SynchronizationContext SynchronizationContext {
+			get {
+				throw new NotImplementedException ();
+			}
+			set {
+			}
+		}
+	}
+}

+ 15 - 0
mcs/class/System.Private.CoreLib/System.Threading/ThreadPool.cs

@@ -0,0 +1,15 @@
+namespace System.Threading
+{
+	partial class ThreadPool
+	{
+		internal static void UnsafeQueueUserWorkItemInternal (object callBack, bool preferLocal) => throw new NotImplementedException ();
+
+		internal static bool TryPopCustomWorkItem (object workItem) => throw new NotImplementedException ();
+
+		public static bool QueueUserWorkItem<TState> (Action<TState> callBack, TState state, bool preferLocal) => throw new NotImplementedException ();
+
+		public static bool UnsafeQueueUserWorkItem<TState> (Action<TState> callBack, TState state, bool preferLocal) => throw new NotImplementedException ();
+
+		public static bool UnsafeQueueUserWorkItem (IThreadPoolWorkItem callBack, bool preferLocal) => throw new NotImplementedException ();
+	}
+}

+ 18 - 0
mcs/class/System.Private.CoreLib/System.Threading/ThreadPoolBoundHandle.cs

@@ -0,0 +1,18 @@
+namespace System.Threading
+{
+	public sealed partial class ThreadPoolBoundHandle : System.IDisposable
+	{
+		internal ThreadPoolBoundHandle() { }
+		public System.Runtime.InteropServices.SafeHandle Handle { get { throw null; } }
+		[System.CLSCompliantAttribute(false)]
+		public unsafe System.Threading.NativeOverlapped* AllocateNativeOverlapped(System.Threading.IOCompletionCallback callback, object state, object pinData) { throw null; }
+		[System.CLSCompliantAttribute(false)]
+		public unsafe System.Threading.NativeOverlapped* AllocateNativeOverlapped(System.Threading.PreAllocatedOverlapped preAllocated) { throw null; }
+		public static System.Threading.ThreadPoolBoundHandle BindHandle(System.Runtime.InteropServices.SafeHandle handle) { throw null; }
+		public void Dispose() { }
+		[System.CLSCompliantAttribute(false)]
+		public unsafe void FreeNativeOverlapped(System.Threading.NativeOverlapped* overlapped) { }
+		[System.CLSCompliantAttribute(false)]
+		public static unsafe object GetNativeOverlappedState(System.Threading.NativeOverlapped* overlapped) { throw null; }
+	}
+}

+ 19 - 0
mcs/class/System.Private.CoreLib/System/Activator.cs

@@ -0,0 +1,19 @@
+namespace System
+{
+	public static partial class Activator
+	{
+		public static System.Runtime.Remoting.ObjectHandle CreateInstance(string assemblyName, string typeName) { throw null; }
+		public static System.Runtime.Remoting.ObjectHandle CreateInstance(string assemblyName, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, object[] args, System.Globalization.CultureInfo culture, object[] activationAttributes) { throw null; }
+		public static System.Runtime.Remoting.ObjectHandle CreateInstance(string assemblyName, string typeName, object[] activationAttributes) { throw null; }
+		public static object CreateInstance(System.Type type) { throw null; }
+		public static object CreateInstance(System.Type type, bool nonPublic) { throw null; }
+		public static object CreateInstance(System.Type type, params object[] args) { throw null; }
+		public static object CreateInstance(System.Type type, object[] args, object[] activationAttributes) { throw null; }
+		public static object CreateInstance(System.Type type, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, object[] args, System.Globalization.CultureInfo culture) { throw null; }
+		public static object CreateInstance(System.Type type, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, object[] args, System.Globalization.CultureInfo culture, object[] activationAttributes) { throw null; }
+		public static System.Runtime.Remoting.ObjectHandle CreateInstanceFrom(string assemblyFile, string typeName) { throw null; }
+		public static System.Runtime.Remoting.ObjectHandle CreateInstanceFrom(string assemblyFile, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, object[] args, System.Globalization.CultureInfo culture, object[] activationAttributes) { throw null; }
+		public static System.Runtime.Remoting.ObjectHandle CreateInstanceFrom(string assemblyFile, string typeName, object[] activationAttributes) { throw null; }
+		public static T CreateInstance<T>() { throw null; }
+	}
+}

+ 10 - 0
mcs/class/System.Private.CoreLib/System/AppContext.cs

@@ -0,0 +1,10 @@
+namespace System
+{
+	partial class AppContext
+	{
+		private static string GetBaseDirectoryCore()
+		{
+			throw new NotImplementedException();
+		}
+	}
+}

+ 9 - 0
mcs/class/System.Private.CoreLib/System/Array.cs

@@ -0,0 +1,9 @@
+namespace System
+{
+	partial class Array
+	{
+		// Will require JIT tweaks to skip constants
+		internal const int MaxArrayLength = 0X7FEFFFFF;
+		internal const int MaxByteArrayLength = 0x7FFFFFC7;
+	}
+}

+ 38 - 0
mcs/class/System.Private.CoreLib/System/Attribute.cs

@@ -0,0 +1,38 @@
+namespace System
+{
+	partial class Attribute
+	{
+        public static System.Attribute GetCustomAttribute(System.Reflection.Assembly element, System.Type attributeType) { throw null; }
+        public static System.Attribute GetCustomAttribute(System.Reflection.Assembly element, System.Type attributeType, bool inherit) { throw null; }
+        public static System.Attribute GetCustomAttribute(System.Reflection.MemberInfo element, System.Type attributeType) { throw null; }
+        public static System.Attribute GetCustomAttribute(System.Reflection.MemberInfo element, System.Type attributeType, bool inherit) { throw null; }
+        public static System.Attribute GetCustomAttribute(System.Reflection.Module element, System.Type attributeType) { throw null; }
+        public static System.Attribute GetCustomAttribute(System.Reflection.Module element, System.Type attributeType, bool inherit) { throw null; }
+        public static System.Attribute GetCustomAttribute(System.Reflection.ParameterInfo element, System.Type attributeType) { throw null; }
+        public static System.Attribute GetCustomAttribute(System.Reflection.ParameterInfo element, System.Type attributeType, bool inherit) { throw null; }
+        public static System.Attribute[] GetCustomAttributes(System.Reflection.Assembly element) { throw null; }
+        public static System.Attribute[] GetCustomAttributes(System.Reflection.Assembly element, bool inherit) { throw null; }
+        public static System.Attribute[] GetCustomAttributes(System.Reflection.Assembly element, System.Type attributeType) { throw null; }
+        public static System.Attribute[] GetCustomAttributes(System.Reflection.Assembly element, System.Type attributeType, bool inherit) { throw null; }
+        public static System.Attribute[] GetCustomAttributes(System.Reflection.MemberInfo element) { throw null; }
+        public static System.Attribute[] GetCustomAttributes(System.Reflection.MemberInfo element, bool inherit) { throw null; }
+        public static System.Attribute[] GetCustomAttributes(System.Reflection.MemberInfo element, System.Type type) { throw null; }
+        public static System.Attribute[] GetCustomAttributes(System.Reflection.MemberInfo element, System.Type type, bool inherit) { throw null; }
+        public static System.Attribute[] GetCustomAttributes(System.Reflection.Module element) { throw null; }
+        public static System.Attribute[] GetCustomAttributes(System.Reflection.Module element, bool inherit) { throw null; }
+        public static System.Attribute[] GetCustomAttributes(System.Reflection.Module element, System.Type attributeType) { throw null; }
+        public static System.Attribute[] GetCustomAttributes(System.Reflection.Module element, System.Type attributeType, bool inherit) { throw null; }
+        public static System.Attribute[] GetCustomAttributes(System.Reflection.ParameterInfo element) { throw null; }
+        public static System.Attribute[] GetCustomAttributes(System.Reflection.ParameterInfo element, bool inherit) { throw null; }
+        public static System.Attribute[] GetCustomAttributes(System.Reflection.ParameterInfo element, System.Type attributeType) { throw null; }
+        public static System.Attribute[] GetCustomAttributes(System.Reflection.ParameterInfo element, System.Type attributeType, bool inherit) { throw null; }
+        public static bool IsDefined(System.Reflection.Assembly element, System.Type attributeType) { throw null; }
+        public static bool IsDefined(System.Reflection.Assembly element, System.Type attributeType, bool inherit) { throw null; }
+        public static bool IsDefined(System.Reflection.MemberInfo element, System.Type attributeType) { throw null; }
+        public static bool IsDefined(System.Reflection.MemberInfo element, System.Type attributeType, bool inherit) { throw null; }
+        public static bool IsDefined(System.Reflection.Module element, System.Type attributeType) { throw null; }
+        public static bool IsDefined(System.Reflection.Module element, System.Type attributeType, bool inherit) { throw null; }
+        public static bool IsDefined(System.Reflection.ParameterInfo element, System.Type attributeType) { throw null; }
+        public static bool IsDefined(System.Reflection.ParameterInfo element, System.Type attributeType, bool inherit) { throw null; }
+    }
+}

+ 13 - 0
mcs/class/System.Private.CoreLib/System/DateTime.cs

@@ -0,0 +1,13 @@
+namespace System
+{
+	partial struct DateTime
+	{
+		internal const bool s_systemSupportsLeapSeconds = false;
+
+		internal static DateTime FromFileTimeLeapSecondsAware (long fileTime) => default (DateTime);
+		internal static long ToFileTimeLeapSecondsAware (long ticks) => default (long);
+
+		// IsValidTimeWithLeapSeconds is not expected to be called at all for now on non-Windows platforms
+		internal static bool IsValidTimeWithLeapSeconds (int year, int month, int day, int hour, int minute, int second, DateTimeKind kind) => false;
+	}
+}

+ 9 - 0
mcs/class/System.Private.CoreLib/System/DefaultBinder.cs

@@ -0,0 +1,9 @@
+namespace System
+{
+	partial class DefaultBinder
+	{
+		private static bool CanChangePrimitive(Type source, Type target) => throw new NotImplementedException ();
+
+		private static bool CanChangePrimitiveObjectToType(object source, Type type) => throw new NotImplementedException ();
+	}
+}

+ 81 - 0
mcs/class/System.Private.CoreLib/System/Environment.cs

@@ -0,0 +1,81 @@
+using System.Globalization;
+
+namespace System
+{
+	partial class Environment
+	{
+#region referencesource dependencies
+		internal static string GetResourceString (string key)
+		{
+			return key;
+		}
+
+		internal static string GetResourceString (string key, CultureInfo culture)
+		{
+			return key;
+		}
+
+		internal static string GetResourceString (string key, params object[] values)
+		{
+			return string.Format (CultureInfo.InvariantCulture, key, values);
+		}
+
+		internal static String GetStackTrace (Exception e, bool needFileInfo)
+		{
+			throw new NotImplementedException ();
+		}
+
+		internal static int GetPageSize () => 0;
+#endregion
+
+		public static string GetEnvironmentVariable (string variable)
+		{
+			throw new NotImplementedException ();
+		}
+
+		internal static string GetResourceStringLocal (string key)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public static string NewLine
+		{
+			get
+			{
+#if PLATFORM_WINDOWS
+				return "\r\n";
+#else
+				return "\n";
+#endif
+			}
+		}
+
+		public static bool HasShutdownStarted
+		{
+			get 
+			{
+				return false;
+			}
+		}
+
+		internal static bool UserInteractive { get; } = false;
+
+		public static int CurrentManagedThreadId { get; } = 1;
+
+		public static int ProcessorCount { get; } = 1;
+
+		public static int TickCount { get; } = 1;
+
+		public static void FailFast (string message)
+		{
+		}
+
+		public static void FailFast(string message, Exception exception)
+		{
+		}
+
+		public static void FailFast (string message, Exception exception, string errorMessage)
+		{
+		}
+	}
+}

+ 22 - 0
mcs/class/System.Private.CoreLib/System/Exception.cs

@@ -0,0 +1,22 @@
+using System.Runtime.Serialization;
+
+namespace System
+{
+	partial class Exception
+	{
+		protected event EventHandler<SafeSerializationEventArgs> SerializeObjectState;
+
+		internal readonly struct DispatchState
+		{
+		}
+
+		internal DispatchState CaptureDispatchState ()
+		{
+			throw new NotImplementedException ();
+		}
+
+		internal void RestoreDispatchState (DispatchState state)
+		{
+		}
+	}
+}

+ 10 - 0
mcs/class/System.Private.CoreLib/System/Math.cs

@@ -0,0 +1,10 @@
+namespace System
+{
+	partial class Math
+	{
+		public static double FusedMultiplyAdd(double x, double y, double z) { throw null; }
+		public static int ILogB(double x) { throw null; }
+		public static double Log2(double x) { throw null; }
+		public static double ScaleB(double x, int n) { throw null; }
+	}
+}

+ 10 - 0
mcs/class/System.Private.CoreLib/System/MathF.cs

@@ -0,0 +1,10 @@
+namespace System
+{
+	partial class MathF
+	{
+		public static float FusedMultiplyAdd(float x, float y, float z) { throw null; }
+		public static int ILogB(float x) { throw null; }
+		public static float Log2(float x) { throw null; }
+		public static float ScaleB(float x, int n) { throw null; }
+	}
+}

+ 10 - 0
mcs/class/System.Private.CoreLib/System/MissingMemberException.cs

@@ -0,0 +1,10 @@
+namespace System
+{
+	partial class MissingMemberException
+	{
+		internal static string FormatSignature (byte[] signature)
+		{
+			return "";
+		}
+	}
+}

+ 25 - 0
mcs/class/System.Private.CoreLib/System/ModuleHandle.cs

@@ -0,0 +1,25 @@
+namespace System
+{
+	public partial struct ModuleHandle
+	{
+		private object _dummy;
+		public static readonly System.ModuleHandle EmptyHandle;
+		public int MDStreamVersion { get { throw null; } }
+		public bool Equals(System.ModuleHandle handle) { throw null; }
+		public override bool Equals(object obj) { throw null; }
+		public override int GetHashCode() { throw null; }
+		public System.RuntimeFieldHandle GetRuntimeFieldHandleFromMetadataToken(int fieldToken) { throw null; }
+		public System.RuntimeMethodHandle GetRuntimeMethodHandleFromMetadataToken(int methodToken) { throw null; }
+		public System.RuntimeTypeHandle GetRuntimeTypeHandleFromMetadataToken(int typeToken) { throw null; }
+		public static bool operator ==(System.ModuleHandle left, System.ModuleHandle right) { throw null; }
+		public static bool operator !=(System.ModuleHandle left, System.ModuleHandle right) { throw null; }
+		public System.RuntimeFieldHandle ResolveFieldHandle(int fieldToken) { throw null; }
+		public System.RuntimeFieldHandle ResolveFieldHandle(int fieldToken, System.RuntimeTypeHandle[] typeInstantiationContext, System.RuntimeTypeHandle[] methodInstantiationContext) { throw null; }
+		public System.RuntimeMethodHandle ResolveMethodHandle(int methodToken) { throw null; }
+		public System.RuntimeMethodHandle ResolveMethodHandle(int methodToken, System.RuntimeTypeHandle[] typeInstantiationContext, System.RuntimeTypeHandle[] methodInstantiationContext) { throw null; }
+		public System.RuntimeTypeHandle ResolveTypeHandle(int typeToken) { throw null; }
+		public System.RuntimeTypeHandle ResolveTypeHandle(int typeToken, System.RuntimeTypeHandle[] typeInstantiationContext, System.RuntimeTypeHandle[] methodInstantiationContext) { throw null; }
+
+		public IntPtr Value => throw new NotImplementedException ();
+	}
+}

+ 34 - 0
mcs/class/System.Private.CoreLib/System/NotImplemented.cs

@@ -0,0 +1,34 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+namespace System
+{
+    //
+    // This simple class enables one to throw a NotImplementedException using the following
+    // idiom:
+    //
+    //     throw NotImplemented.ByDesign;
+    //
+    // Used by methods whose intended implementation is to throw a NotImplementedException (typically
+    // virtual methods in public abstract classes that intended to be subclassed by third parties.)
+    //
+    // This makes it distinguishable both from human eyes and CCI from NYI's that truly represent undone work.
+    //
+    internal static class NotImplemented
+    {
+        internal static Exception ByDesign
+        {
+            get
+            {
+                return new NotImplementedException();
+            }
+        }
+
+        internal static Exception ByDesignWithMessage(string message)
+        {
+            return new NotImplementedException(message);
+        }
+    }
+}
+

+ 17 - 0
mcs/class/System.Private.CoreLib/System/Object.cs

@@ -0,0 +1,17 @@
+using System.Runtime.CompilerServices;
+
+namespace System
+{
+	partial class Object
+	{
+		[MethodImplAttribute (MethodImplOptions.InternalCall)]
+		public extern Type GetType ();
+
+		[MethodImplAttribute (MethodImplOptions.InternalCall)]
+		protected extern object MemberwiseClone ();
+
+		// TODO: Move to RuntimeHelpers
+		[MethodImplAttribute (MethodImplOptions.InternalCall)]
+		internal static extern int InternalGetHashCode (object o);
+	}
+}

+ 14 - 0
mcs/class/System.Private.CoreLib/System/RuntimeFieldHandle.cs

@@ -0,0 +1,14 @@
+namespace System
+{
+	public partial struct RuntimeFieldHandle : System.Runtime.Serialization.ISerializable
+	{
+		private object _dummy;
+		public System.IntPtr Value { get { throw null; } }
+		public override bool Equals(object obj) { throw null; }
+		public bool Equals(System.RuntimeFieldHandle handle) { throw null; }
+		public override int GetHashCode() { throw null; }
+		public void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
+		public static bool operator ==(System.RuntimeFieldHandle left, System.RuntimeFieldHandle right) { throw null; }
+		public static bool operator !=(System.RuntimeFieldHandle left, System.RuntimeFieldHandle right) { throw null; }
+	}
+}

+ 19 - 0
mcs/class/System.Private.CoreLib/System/RuntimeMethodHandle.cs

@@ -0,0 +1,19 @@
+namespace System
+{
+	public partial struct RuntimeMethodHandle : System.Runtime.Serialization.ISerializable
+	{
+		private object _dummy;
+		public System.IntPtr Value { get { throw null; } }
+		public override bool Equals(object obj) { throw null; }
+		public bool Equals(System.RuntimeMethodHandle handle) { throw null; }
+		public System.IntPtr GetFunctionPointer() { throw null; }
+		public override int GetHashCode() { throw null; }
+		public void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
+		public static bool operator ==(System.RuntimeMethodHandle left, System.RuntimeMethodHandle right) { throw null; }
+		public static bool operator !=(System.RuntimeMethodHandle left, System.RuntimeMethodHandle right) { throw null; }
+
+		internal RuntimeMethodHandle (IntPtr ptr)
+		{
+		}
+	}
+}

+ 26 - 0
mcs/class/System.Private.CoreLib/System/RuntimeTypeHandle.cs

@@ -0,0 +1,26 @@
+namespace System
+{
+	public partial struct RuntimeTypeHandle : System.Runtime.Serialization.ISerializable
+	{
+		private object _dummy;
+		public System.IntPtr Value { get { throw null; } }
+		public override bool Equals(object obj) { throw null; }
+		public bool Equals(System.RuntimeTypeHandle handle) { throw null; }
+		public override int GetHashCode() { throw null; }
+		public System.ModuleHandle GetModuleHandle() { throw null; }
+		public void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
+		public static bool operator ==(object left, System.RuntimeTypeHandle right) { throw null; }
+		public static bool operator ==(System.RuntimeTypeHandle left, object right) { throw null; }
+		public static bool operator !=(object left, System.RuntimeTypeHandle right) { throw null; }
+		public static bool operator !=(System.RuntimeTypeHandle left, object right) { throw null; }
+
+
+		public RuntimeTypeHandle (IntPtr ptr)
+		{           
+		}
+
+		public static bool HasReferences (RuntimeType rt) => false;
+
+		public static bool IsInterface (RuntimeType rt) => false;
+	}
+}

+ 102 - 0
mcs/class/System.Private.CoreLib/System/Type.cs

@@ -0,0 +1,102 @@
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+namespace System
+{
+	partial class Type
+	{
+		public static Type GetTypeFromCLSID (Guid clsid, string server, bool throwOnError) => throw new NotImplementedException ();
+		public static Type GetTypeFromProgID (string progID, string server, bool throwOnError) => throw new NotImplementedException ();
+
+		internal bool IsRuntimeImplemented () => this.UnderlyingSystemType is RuntimeType;
+
+		internal string FullNameOrDefault {
+			get {
+				throw new NotImplementedException ();
+			}
+		}
+
+		internal string NameOrDefault {
+			get {
+				throw new NotImplementedException ();
+			}
+		}
+
+		public bool IsInterface {
+			get {
+				RuntimeType rt = this as RuntimeType;
+				if (rt != null)
+					return RuntimeTypeHandle.IsInterface (rt);
+				return ((GetAttributeFlagsImpl() & TypeAttributes.ClassSemanticsMask) == TypeAttributes.Interface);
+			}
+		}
+
+		public static Type GetType (String typeName, bool throwOnError, bool ignoreCase)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public static Type GetType (String typeName, bool throwOnError)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public static Type GetType (String typeName)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public static Type GetType (
+			string typeName,
+			Func<AssemblyName, Assembly> assemblyResolver,
+			Func<Assembly, string, bool, Type> typeResolver)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public static Type GetType (
+			string typeName,
+			Func<AssemblyName, Assembly> assemblyResolver,
+			Func<Assembly, string, bool, Type> typeResolver,
+			bool throwOnError)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public static Type GetType(
+			string typeName,
+			Func<AssemblyName, Assembly> assemblyResolver,
+			Func<Assembly, string, bool, Type> typeResolver,
+			bool throwOnError,
+			bool ignoreCase)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public static Type GetTypeFromHandle (RuntimeTypeHandle handle)
+		{
+			if (handle.Value == IntPtr.Zero)
+				// This is not consistent with the other GetXXXFromHandle methods, but
+				// MS.NET seems to do this
+				return null;
+
+			return internal_from_handle (handle.Value);
+		}
+
+		internal string FormatTypeName () => throw new NotImplementedException ();
+
+		[MethodImplAttribute (MethodImplOptions.InternalCall)]
+		static extern Type internal_from_handle (IntPtr handle);
+
+		public static bool operator == (Type left, Type right)
+		{
+			return object.ReferenceEquals (left, right);
+		}
+
+		public static bool operator != (Type left, Type right)
+		{
+			return !object.ReferenceEquals (left, right);
+		}
+	}
+}

+ 43 - 0
mcs/class/System.Private.CoreLib/temp/AsyncCausalitySupport.cs

@@ -0,0 +1,43 @@
+using System.Threading.Tasks;
+
+namespace Internal.Threading.Tasks
+{
+	public static class AsyncCausalitySupport
+	{
+		public static void AddToActiveTasks(Task task)
+		{
+		}
+
+		public static void RemoveFromActiveTasks(Task task)
+		{
+		}
+
+		public static bool LoggingOn
+		{
+			get
+			{
+				return false;
+			}
+		}
+
+		public static void TraceOperationCreation(Task task, string operationName)
+		{
+		}
+
+		public static void TraceOperationCompletedSuccess(Task task)
+		{
+		}
+
+		public static void TraceOperationCompletedError(Task task)
+		{
+		}
+
+		public static void TraceSynchronousWorkStart(Task task)
+		{
+		}
+
+		public static void TraceSynchronousWorkCompletion()
+		{
+		}
+	}
+}

+ 46 - 0
mcs/class/System.Private.CoreLib/temp/AsyncCausalityTracer.cs

@@ -0,0 +1,46 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+
+namespace Internal.Runtime.Augments
+{
+    public enum CausalityRelation
+    {
+        AssignDelegate = 0,
+        Join = 1,
+        Choice = 2,
+        Cancel = 3,
+        Error = 4,
+    }
+
+    public enum CausalitySource
+    {
+        Application = 0,
+        Library = 1,
+        System = 2,
+    }
+
+    public enum CausalityTraceLevel
+    {
+        Required = 0,
+        Important = 1,
+        Verbose = 2,
+    }
+
+    public enum AsyncStatus
+    {
+        Started = 0,
+        Completed = 1,
+        Canceled = 2,
+        Error = 3,
+    }
+
+    public enum CausalitySynchronousWork
+    {
+        CompletionNotification = 0,
+        ProgressNotification = 1,
+        Execution = 2,
+    }
+}

+ 388 - 0
mcs/class/System.Private.CoreLib/temp/ContractBCL.cs

@@ -0,0 +1,388 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+/*============================================================
+**
+** 
+**
+** Implementation details of CLR Contracts.
+**
+===========================================================*/
+#define DEBUG // The behavior of this contract library should be consistent regardless of build type.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
+using System.Diagnostics.Contracts;
+using System.Reflection;
+
+namespace System.Diagnostics.Contracts
+{
+    public static partial class Contract
+    {
+        #region Private Methods
+
+        /// <summary>
+        /// This method is used internally to trigger a failure indicating to the "programmer" that he is using the interface incorrectly.
+        /// It is NEVER used to indicate failure of actual contracts at runtime.
+        /// </summary>
+        static void AssertMustUseRewriter(ContractFailureKind kind, string contractKind)
+        {
+            // For better diagnostics, report which assembly is at fault.  Walk up stack and
+            // find the first non-mscorlib assembly.
+            Assembly thisAssembly = typeof(Contract).Assembly;  // In case we refactor mscorlib, use Contract class instead of Object.
+            StackTrace stack = new StackTrace();
+            Assembly probablyNotRewritten = null;
+            for (int i = 0; i < stack.FrameCount; i++)
+            {
+                Assembly caller = stack.GetFrame(i).GetMethod().DeclaringType.Assembly;
+                if (caller != thisAssembly)
+                {
+                    probablyNotRewritten = caller;
+                    break;
+                }
+            }
+
+            if (probablyNotRewritten == null)
+                probablyNotRewritten = thisAssembly;
+            string simpleName = probablyNotRewritten.GetName().Name;
+            System.Runtime.CompilerServices.ContractHelper.TriggerFailure(kind, SR.Format(SR.MustUseCCRewrite, contractKind, simpleName), null, null, null);
+        }
+
+        #endregion Private Methods
+
+        #region Failure Behavior
+
+        /// <summary>
+        /// Without contract rewriting, failing Assert/Assumes end up calling this method.
+        /// Code going through the contract rewriter never calls this method. Instead, the rewriter produced failures call
+        /// System.Runtime.CompilerServices.ContractHelper.RaiseContractFailedEvent, followed by 
+        /// System.Runtime.CompilerServices.ContractHelper.TriggerFailure.
+        /// </summary>
+        [System.Diagnostics.DebuggerNonUserCode]
+        static void ReportFailure(ContractFailureKind failureKind, string userMessage, string conditionText, Exception innerException)
+        {
+            if (failureKind < ContractFailureKind.Precondition || failureKind > ContractFailureKind.Assume)
+                throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, failureKind), nameof(failureKind));
+
+            // displayMessage == null means: yes we handled it. Otherwise it is the localized failure message
+            var displayMessage = System.Runtime.CompilerServices.ContractHelper.RaiseContractFailedEvent(failureKind, userMessage, conditionText, innerException);
+
+            if (displayMessage == null) return;
+
+            System.Runtime.CompilerServices.ContractHelper.TriggerFailure(failureKind, displayMessage, userMessage, conditionText, innerException);
+        }
+
+        /// <summary>
+        /// Allows a managed application environment such as an interactive interpreter (IronPython)
+        /// to be notified of contract failures and 
+        /// potentially "handle" them, either by throwing a particular exception type, etc.  If any of the
+        /// event handlers sets the Cancel flag in the ContractFailedEventArgs, then the Contract class will
+        /// not pop up an assert dialog box or trigger escalation policy.  Hooking this event requires 
+        /// full trust, because it will inform you of bugs in the appdomain and because the event handler
+        /// could allow you to continue execution.
+        /// </summary>
+        public static event EventHandler<ContractFailedEventArgs> ContractFailed
+        {
+            add
+            {
+                System.Runtime.CompilerServices.ContractHelper.InternalContractFailed += value;
+            }
+            remove
+            {
+                System.Runtime.CompilerServices.ContractHelper.InternalContractFailed -= value;
+            }
+        }
+        #endregion FailureBehavior
+    }
+
+    public sealed class ContractFailedEventArgs : EventArgs
+    {
+        private ContractFailureKind _failureKind;
+        private string _message;
+        private string _condition;
+        private Exception _originalException;
+        private bool _handled;
+        private bool _unwind;
+
+        internal Exception thrownDuringHandler;
+
+        public ContractFailedEventArgs(ContractFailureKind failureKind, string message, string condition, Exception originalException)
+        {
+            Debug.Assert(originalException == null || failureKind == ContractFailureKind.PostconditionOnException);
+            _failureKind = failureKind;
+            _message = message;
+            _condition = condition;
+            _originalException = originalException;
+        }
+
+        public string Message { get { return _message; } }
+        public string Condition { get { return _condition; } }
+        public ContractFailureKind FailureKind { get { return _failureKind; } }
+        public Exception OriginalException { get { return _originalException; } }
+
+        // Whether the event handler "handles" this contract failure, or to fail via escalation policy.
+        public bool Handled
+        {
+            get { return _handled; }
+        }
+
+        public void SetHandled()
+        {
+            _handled = true;
+        }
+
+        public bool Unwind
+        {
+            get { return _unwind; }
+        }
+
+        public void SetUnwind()
+        {
+            _unwind = true;
+        }
+    }
+
+    [Serializable]
+    [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
+    // Needs to be public to support binary serialization compatibility
+    public sealed class ContractException : Exception
+    {
+        private readonly ContractFailureKind _kind;
+        private readonly string _userMessage;
+        private readonly string _condition;
+
+        public ContractFailureKind Kind { get { return _kind; } }
+        public string Failure { get { return this.Message; } }
+        public string UserMessage { get { return _userMessage; } }
+        public string Condition { get { return _condition; } }
+
+        // Called by COM Interop, if we see COR_E_CODECONTRACTFAILED as an HRESULT.
+        private ContractException()
+        {
+            HResult = System.Runtime.CompilerServices.ContractHelper.COR_E_CODECONTRACTFAILED;
+        }
+
+        public ContractException(ContractFailureKind kind, string failure, string userMessage, string condition, Exception innerException)
+            : base(failure, innerException)
+        {
+            HResult = System.Runtime.CompilerServices.ContractHelper.COR_E_CODECONTRACTFAILED;
+            _kind = kind;
+            _userMessage = userMessage;
+            _condition = condition;
+        }
+
+        private ContractException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
+            : base(info, context)
+        {
+            _kind = (ContractFailureKind)info.GetInt32("Kind");
+            _userMessage = info.GetString("UserMessage");
+            _condition = info.GetString("Condition");
+        }
+
+
+        public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
+        {
+            base.GetObjectData(info, context);
+            info.AddValue("Kind", _kind);
+            info.AddValue("UserMessage", _userMessage);
+            info.AddValue("Condition", _condition);
+        }
+    }
+}
+
+
+namespace System.Runtime.CompilerServices
+{
+    public static partial class ContractHelper
+    {
+#region Private fields
+
+        private static volatile EventHandler<ContractFailedEventArgs> contractFailedEvent;
+        private static readonly object lockObject = new object();
+
+        internal const int COR_E_CODECONTRACTFAILED = unchecked((int)0x80131542);
+
+#endregion
+
+        /// <summary>
+        /// Allows a managed application environment such as an interactive interpreter (IronPython) or a
+        /// web browser host (Jolt hosting Silverlight in IE) to be notified of contract failures and 
+        /// potentially "handle" them, either by throwing a particular exception type, etc.  If any of the
+        /// event handlers sets the Cancel flag in the ContractFailedEventArgs, then the Contract class will
+        /// not pop up an assert dialog box or trigger escalation policy.  Hooking this event requires 
+        /// full trust.
+        /// </summary>
+        internal static event EventHandler<ContractFailedEventArgs> InternalContractFailed
+        {
+            add
+            {
+                // Eagerly prepare each event handler _marked with a reliability contract_, to 
+                // attempt to reduce out of memory exceptions while reporting contract violations.
+                // This only works if the new handler obeys the constraints placed on 
+                // constrained execution regions.  Eagerly preparing non-reliable event handlers
+                // would be a perf hit and wouldn't significantly improve reliability.
+                // UE: Please mention reliable event handlers should also be marked with the 
+                // PrePrepareMethodAttribute to avoid CER eager preparation work when ngen'ed.
+                System.Runtime.CompilerServices.RuntimeHelpers.PrepareContractedDelegate(value);
+                lock (lockObject)
+                {
+                    contractFailedEvent += value;
+                }
+            }
+            remove
+            {
+                lock (lockObject)
+                {
+                    contractFailedEvent -= value;
+                }
+            }
+        }
+
+        /// <summary>
+        /// Rewriter will call this method on a contract failure to allow listeners to be notified.
+        /// The method should not perform any failure (assert/throw) itself.
+        /// This method has 3 functions:
+        /// 1. Call any contract hooks (such as listeners to Contract failed events)
+        /// 2. Determine if the listeners deem the failure as handled (then resultFailureMessage should be set to null)
+        /// 3. Produce a localized resultFailureMessage used in advertising the failure subsequently.
+        /// On exit: null if the event was handled and should not trigger a failure.
+        ///          Otherwise, returns the localized failure message.
+        /// </summary>
+        [System.Diagnostics.DebuggerNonUserCode]
+        public static string RaiseContractFailedEvent(ContractFailureKind failureKind, string userMessage, string conditionText, Exception innerException)
+        {
+            if (failureKind < ContractFailureKind.Precondition || failureKind > ContractFailureKind.Assume)
+                throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, failureKind), nameof(failureKind));
+
+            string returnValue;
+            string displayMessage = "contract failed.";  // Incomplete, but in case of OOM during resource lookup...
+            ContractFailedEventArgs eventArgs = null;  // In case of OOM.
+
+            try
+            {
+                displayMessage = GetDisplayMessage(failureKind, userMessage, conditionText);
+                EventHandler<ContractFailedEventArgs> contractFailedEventLocal = contractFailedEvent;
+                if (contractFailedEventLocal != null)
+                {
+                    eventArgs = new ContractFailedEventArgs(failureKind, displayMessage, conditionText, innerException);
+                    foreach (EventHandler<ContractFailedEventArgs> handler in contractFailedEventLocal.GetInvocationList())
+                    {
+                        try
+                        {
+                            handler(null, eventArgs);
+                        }
+                        catch (Exception e)
+                        {
+                            eventArgs.thrownDuringHandler = e;
+                            eventArgs.SetUnwind();
+                        }
+                    }
+                    if (eventArgs.Unwind)
+                    {
+                        // unwind
+                        if (innerException == null) { innerException = eventArgs.thrownDuringHandler; }
+                        throw new ContractException(failureKind, displayMessage, userMessage, conditionText, innerException);
+                    }
+                }
+            }
+            finally
+            {
+                if (eventArgs != null && eventArgs.Handled)
+                {
+                    returnValue = null; // handled
+                }
+                else
+                {
+                    returnValue = displayMessage;
+                }
+            }
+            return returnValue;
+        }
+
+        /// <summary>
+        /// Rewriter calls this method to get the default failure behavior.
+        /// </summary>
+        [System.Diagnostics.DebuggerNonUserCode]
+        public static void TriggerFailure(ContractFailureKind kind, string displayMessage, string userMessage, string conditionText, Exception innerException)
+        {
+            if (string.IsNullOrEmpty(displayMessage))
+            {
+                displayMessage = GetDisplayMessage(kind, userMessage, conditionText);
+            }
+
+            System.Diagnostics.Debug.ContractFailure(false, displayMessage, string.Empty, GetResourceNameForFailure(kind));
+        }
+
+        private static string GetResourceNameForFailure(ContractFailureKind failureKind)
+        {
+            string resourceName = null;
+            switch (failureKind)
+            {
+                case ContractFailureKind.Assert:
+                    resourceName = "AssertionFailed";
+                    break;
+
+                case ContractFailureKind.Assume:
+                    resourceName = "AssumptionFailed";
+                    break;
+
+                case ContractFailureKind.Precondition:
+                    resourceName = "PreconditionFailed";
+                    break;
+
+                case ContractFailureKind.Postcondition:
+                    resourceName = "PostconditionFailed";
+                    break;
+
+                case ContractFailureKind.Invariant:
+                    resourceName = "InvariantFailed";
+                    break;
+
+                case ContractFailureKind.PostconditionOnException:
+                    resourceName = "PostconditionOnExceptionFailed";
+                    break;
+
+                default:
+                    Debug.Fail("Unreachable code");
+                    resourceName = "AssumptionFailed";
+                    break;
+            }
+            return resourceName;
+        }
+
+        private static string GetDisplayMessage(ContractFailureKind failureKind, string userMessage, string conditionText)
+        {
+            string failureMessage;
+            // Well-formatted English messages will take one of four forms.  A sentence ending in
+            // either a period or a colon, the condition string, then the message tacked 
+            // on to the end with two spaces in front.
+            // Note that both the conditionText and userMessage may be null.  Also, 
+            // on Silverlight we may not be able to look up a friendly string for the
+            // error message.  Let's leverage Silverlight's default error message there. 
+            if (!string.IsNullOrEmpty(conditionText))
+            {
+                string resourceName = GetResourceNameForFailure(failureKind); 
+                resourceName += "_Cnd";
+                failureMessage = SR.Format(SR.GetResourceString(resourceName), conditionText);
+            }
+            else
+            {
+                failureMessage = "";
+            }
+
+            // Now add in the user message, if present.
+            if (!string.IsNullOrEmpty(userMessage))
+            {
+                return failureMessage + "  " + userMessage;
+            }
+            else
+            {
+                return failureMessage;
+            }
+        }
+    }
+}  // namespace System.Runtime.CompilerServices
+

+ 45 - 0
mcs/class/System.Private.CoreLib/temp/DebuggerSupport.Dummy.cs

@@ -0,0 +1,45 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using AsyncStatus = Internal.Runtime.Augments.AsyncStatus;
+using CausalityRelation = Internal.Runtime.Augments.CausalityRelation;
+using CausalityTraceLevel = Internal.Runtime.Augments.CausalityTraceLevel;
+using CausalitySynchronousWork = Internal.Runtime.Augments.CausalitySynchronousWork;
+
+namespace System.Threading.Tasks
+{
+    //
+    // Dummy implementation of AsyncCausality events
+    //
+    internal static partial class DebuggerSupport
+    {
+        public static bool LoggingOn
+        {
+            get
+            {
+                return false;
+            }
+        }
+
+        public static void TraceOperationCreation(CausalityTraceLevel traceLevel, Task task, String operationName, ulong relatedContext)
+        {
+        }
+
+        public static void TraceOperationCompletion(CausalityTraceLevel traceLevel, Task task, AsyncStatus status)
+        {
+        }
+
+        public static void TraceOperationRelation(CausalityTraceLevel traceLevel, Task task, CausalityRelation relation)
+        {
+        }
+
+        public static void TraceSynchronousWorkStart(CausalityTraceLevel traceLevel, Task task, CausalitySynchronousWork work)
+        {
+        }
+
+        public static void TraceSynchronousWorkCompletion(CausalityTraceLevel traceLevel, CausalitySynchronousWork work)
+        {
+        }
+    }
+}

+ 69 - 0
mcs/class/System.Private.CoreLib/temp/DebuggerSupport.Mono.cs

@@ -0,0 +1,69 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Collections.Generic;
+using System.Runtime.CompilerServices;
+
+namespace System.Threading.Tasks
+{
+    //
+    // This class encapsulates the infrastructure to emit AsyncCausality events and Task-ID tracking for the use of the debugger.
+    //
+    internal static partial class DebuggerSupport
+    {
+        //==============================================================================================================
+        // This section of the class tracks adds the ability to retrieve an active Task from its ID. The debugger
+        // is only component that needs this tracking so we only enable it when the debugger specifically requests it
+        // by setting Task.s_asyncDebuggingEnabled.
+        //==============================================================================================================
+        [MethodImpl(MethodImplOptions.AggressiveInlining)]
+        public static void AddToActiveTasks(Task task)
+        {
+        }
+
+        [MethodImpl(MethodImplOptions.NoInlining)]
+        private static void AddToActiveTasksNonInlined(Task task)
+        {
+        }
+
+        [MethodImpl(MethodImplOptions.AggressiveInlining)]
+        public static void RemoveFromActiveTasks(Task task)
+        {
+        }
+
+        [MethodImpl(MethodImplOptions.NoInlining)]
+        private static void RemoveFromActiveTasksNonInlined(Task task)
+        {
+        }
+
+        [MethodImpl(MethodImplOptions.AggressiveInlining)]
+        public static Task GetActiveTaskFromId(int taskId)
+        {
+            Task task = null;
+            return task;
+        }
+
+        //==============================================================================================================
+        // This section of the class wraps calls to get the lazy-created Task object for the purpose of reporting
+        // async causality events to the debugger.
+        //==============================================================================================================
+        [MethodImpl(MethodImplOptions.AggressiveInlining)]
+        public static Task GetTaskIfDebuggingEnabled(this AsyncVoidMethodBuilder builder)
+        {
+                return null;
+        }
+
+        [MethodImpl(MethodImplOptions.AggressiveInlining)]
+        public static Task GetTaskIfDebuggingEnabled(this AsyncTaskMethodBuilder builder)
+        {
+                return null;
+        }
+
+        [MethodImpl(MethodImplOptions.AggressiveInlining)]
+        public static Task GetTaskIfDebuggingEnabled<TResult>(this AsyncTaskMethodBuilder<TResult> builder)
+        {
+                return null;
+        }
+    }
+}

+ 40 - 0
mcs/class/System.Private.CoreLib/temp/EnvironmentAugments.cs

@@ -0,0 +1,40 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Runtime.CompilerServices;
+
+namespace Internal.Runtime.Augments
+{
+    /// <summary>For internal use only.  Exposes runtime functionality to the Environments implementation in corefx.</summary>
+    public static class EnvironmentAugments
+    {
+        public static int CurrentManagedThreadId => Environment.CurrentManagedThreadId;
+        public static void Exit(int exitCode) => throw new NotImplementedException();
+        public static int ExitCode { get { throw new NotImplementedException(); } set { } }
+        public static void FailFast(string message, Exception error) => Environment.FailFast(message, error);
+        public static string[] GetCommandLineArgs() => throw new NotImplementedException();
+        public static bool HasShutdownStarted => Environment.HasShutdownStarted;
+        public static int TickCount => Environment.TickCount;
+        public static string GetEnvironmentVariable(string variable) => Environment.GetEnvironmentVariable(variable);
+        public static string GetEnvironmentVariable(string variable, EnvironmentVariableTarget target) => throw new NotImplementedException();
+        public static IEnumerable<KeyValuePair<string, string>> EnumerateEnvironmentVariables() => throw new NotImplementedException();
+        public static IEnumerable<KeyValuePair<string, string>> EnumerateEnvironmentVariables(EnvironmentVariableTarget target) => throw new NotImplementedException();
+        public static int ProcessorCount => Environment.ProcessorCount;
+
+        public static void SetEnvironmentVariable(string variable, string value) => throw new NotImplementedException();
+        public static void SetEnvironmentVariable(string variable, string value, EnvironmentVariableTarget target) => throw new NotImplementedException();
+
+        public static string StackTrace
+        {
+            [MethodImpl(MethodImplOptions.NoInlining)] // Prevent inlining from affecting where the stacktrace starts
+            get
+            {
+                return new StackTrace(1 /* skip this one frame */, true).ToString(System.Diagnostics.StackTrace.TraceFormat.Normal);
+            }
+        }
+    }
+}

+ 2106 - 0
mcs/class/System.Private.CoreLib/temp/FutureFactory.cs

@@ -0,0 +1,2106 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
+//
+//
+//
+// As with TaskFactory, TaskFactory<TResult> encodes common factory patterns into helper methods.
+//
+// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
+
+using System.Diagnostics;
+
+using AsyncStatus = Internal.Runtime.Augments.AsyncStatus;
+using CausalityRelation = Internal.Runtime.Augments.CausalityRelation;
+using CausalitySource = Internal.Runtime.Augments.CausalitySource;
+using CausalityTraceLevel = Internal.Runtime.Augments.CausalityTraceLevel;
+using CausalitySynchronousWork = Internal.Runtime.Augments.CausalitySynchronousWork;
+
+namespace System.Threading.Tasks
+{
+    /// <summary>
+    /// Provides support for creating and scheduling
+    /// <see cref="T:System.Threading.Tasks.Task{TResult}">Task{TResult}</see> objects.
+    /// </summary>
+    /// <typeparam name="TResult">The type of the results that are available though 
+    /// the <see cref="T:System.Threading.Tasks.Task{TResult}">Task{TResult}</see> objects that are associated with 
+    /// the methods in this class.</typeparam>
+    /// <remarks>
+    /// <para>
+    /// There are many common patterns for which tasks are relevant. The <see cref="TaskFactory{TResult}"/>
+    /// class encodes some of these patterns into methods that pick up default settings, which are
+    /// configurable through its constructors.
+    /// </para>
+    /// <para>
+    /// A default instance of <see cref="TaskFactory{TResult}"/> is available through the
+    /// <see cref="System.Threading.Tasks.Task{TResult}.Factory">Task{TResult}.Factory</see> property.
+    /// </para>
+    /// </remarks>
+    public class TaskFactory<TResult>
+    {
+        // Member variables, DefaultScheduler, other properties and ctors 
+        // copied right out of TaskFactory...  Lots of duplication here...
+        // Should we be thinking about a TaskFactoryBase class?
+
+        // member variables
+        private CancellationToken m_defaultCancellationToken;
+        private TaskScheduler m_defaultScheduler;
+        private TaskCreationOptions m_defaultCreationOptions;
+        private TaskContinuationOptions m_defaultContinuationOptions;
+
+        private TaskScheduler DefaultScheduler
+        {
+            get
+            {
+                if (m_defaultScheduler == null) return TaskScheduler.Current;
+                else return m_defaultScheduler;
+            }
+        }
+
+        // sister method to above property -- avoids a TLS lookup
+        private TaskScheduler GetDefaultScheduler(Task currTask)
+        {
+            if (m_defaultScheduler != null) return m_defaultScheduler;
+            else if ((currTask != null)
+                && ((currTask.CreationOptions & TaskCreationOptions.HideScheduler) == 0)
+                )
+                return currTask.ExecutingTaskScheduler;
+            else return TaskScheduler.Default;
+        }
+
+        /* Constructors */
+
+        /// <summary>
+        /// Initializes a <see cref="TaskFactory{TResult}"/> instance with the default configuration.
+        /// </summary>
+        /// <remarks>
+        /// This constructor creates a <see cref="TaskFactory{TResult}"/> instance with a default configuration. The
+        /// <see cref="TaskCreationOptions"/> property is initialized to
+        /// <see cref="System.Threading.Tasks.TaskCreationOptions.None">TaskCreationOptions.None</see>, the
+        /// <see cref="TaskContinuationOptions"/> property is initialized to <see
+        /// cref="System.Threading.Tasks.TaskContinuationOptions.None">TaskContinuationOptions.None</see>,
+        /// and the <see cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see> property is
+        /// initialized to the current scheduler (see <see
+        /// cref="System.Threading.Tasks.TaskScheduler.Current">TaskScheduler.Current</see>).
+        /// </remarks>
+        public TaskFactory()
+            : this(default, TaskCreationOptions.None, TaskContinuationOptions.None, null)
+        {
+        }
+
+        /// <summary>
+        /// Initializes a <see cref="TaskFactory{TResult}"/> instance with the default configuration.
+        /// </summary>
+        /// <param name="cancellationToken">The default <see cref="CancellationToken"/> that will be assigned 
+        /// to tasks created by this <see cref="TaskFactory"/> unless another CancellationToken is explicitly specified 
+        /// while calling the factory methods.</param>
+        /// <remarks>
+        /// This constructor creates a <see cref="TaskFactory{TResult}"/> instance with a default configuration. The
+        /// <see cref="TaskCreationOptions"/> property is initialized to
+        /// <see cref="System.Threading.Tasks.TaskCreationOptions.None">TaskCreationOptions.None</see>, the
+        /// <see cref="TaskContinuationOptions"/> property is initialized to <see
+        /// cref="System.Threading.Tasks.TaskContinuationOptions.None">TaskContinuationOptions.None</see>,
+        /// and the <see cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see> property is
+        /// initialized to the current scheduler (see <see
+        /// cref="System.Threading.Tasks.TaskScheduler.Current">TaskScheduler.Current</see>).
+        /// </remarks>
+        public TaskFactory(CancellationToken cancellationToken)
+            : this(cancellationToken, TaskCreationOptions.None, TaskContinuationOptions.None, null)
+        {
+        }
+
+        /// <summary>
+        /// Initializes a <see cref="TaskFactory{TResult}"/> instance with the specified configuration.
+        /// </summary>
+        /// <param name="scheduler">
+        /// The <see cref="System.Threading.Tasks.TaskScheduler">
+        /// TaskScheduler</see> to use to schedule any tasks created with this TaskFactory{TResult}. A null value
+        /// indicates that the current TaskScheduler should be used.
+        /// </param>
+        /// <remarks>
+        /// With this constructor, the
+        /// <see cref="TaskCreationOptions"/> property is initialized to
+        /// <see cref="System.Threading.Tasks.TaskCreationOptions.None">TaskCreationOptions.None</see>, the
+        /// <see cref="TaskContinuationOptions"/> property is initialized to <see
+        /// cref="System.Threading.Tasks.TaskContinuationOptions.None">TaskContinuationOptions.None</see>,
+        /// and the <see cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see> property is
+        /// initialized to <paramref name="scheduler"/>, unless it's null, in which case the property is
+        /// initialized to the current scheduler (see <see
+        /// cref="System.Threading.Tasks.TaskScheduler.Current">TaskScheduler.Current</see>).
+        /// </remarks>
+        public TaskFactory(TaskScheduler scheduler) // null means to use TaskScheduler.Current
+            : this(default, TaskCreationOptions.None, TaskContinuationOptions.None, scheduler)
+        {
+        }
+
+        /// <summary>
+        /// Initializes a <see cref="TaskFactory{TResult}"/> instance with the specified configuration.
+        /// </summary>
+        /// <param name="creationOptions">
+        /// The default <see cref="System.Threading.Tasks.TaskCreationOptions">
+        /// TaskCreationOptions</see> to use when creating tasks with this TaskFactory{TResult}.
+        /// </param>
+        /// <param name="continuationOptions">
+        /// The default <see cref="System.Threading.Tasks.TaskContinuationOptions">
+        /// TaskContinuationOptions</see> to use when creating continuation tasks with this TaskFactory{TResult}.
+        /// </param>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">
+        /// The exception that is thrown when the
+        /// <paramref name="creationOptions"/> argument or the <paramref name="continuationOptions"/>
+        /// argument specifies an invalid value.
+        /// </exception>
+        /// <remarks>
+        /// With this constructor, the
+        /// <see cref="TaskCreationOptions"/> property is initialized to <paramref name="creationOptions"/>,
+        /// the
+        /// <see cref="TaskContinuationOptions"/> property is initialized to <paramref
+        /// name="continuationOptions"/>, and the <see
+        /// cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see> property is initialized to the
+        /// current scheduler (see <see
+        /// cref="System.Threading.Tasks.TaskScheduler.Current">TaskScheduler.Current</see>).
+        /// </remarks>
+        public TaskFactory(TaskCreationOptions creationOptions, TaskContinuationOptions continuationOptions)
+            : this(default, creationOptions, continuationOptions, null)
+        {
+        }
+
+        /// <summary>
+        /// Initializes a <see cref="TaskFactory{TResult}"/> instance with the specified configuration.
+        /// </summary>
+        /// <param name="cancellationToken">The default <see cref="CancellationToken"/> that will be assigned 
+        /// to tasks created by this <see cref="TaskFactory"/> unless another CancellationToken is explicitly specified 
+        /// while calling the factory methods.</param>
+        /// <param name="creationOptions">
+        /// The default <see cref="System.Threading.Tasks.TaskCreationOptions">
+        /// TaskCreationOptions</see> to use when creating tasks with this TaskFactory{TResult}.
+        /// </param>
+        /// <param name="continuationOptions">
+        /// The default <see cref="System.Threading.Tasks.TaskContinuationOptions">
+        /// TaskContinuationOptions</see> to use when creating continuation tasks with this TaskFactory{TResult}.
+        /// </param>
+        /// <param name="scheduler">
+        /// The default <see cref="System.Threading.Tasks.TaskScheduler">
+        /// TaskScheduler</see> to use to schedule any Tasks created with this TaskFactory{TResult}. A null value
+        /// indicates that TaskScheduler.Current should be used.
+        /// </param>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">
+        /// The exception that is thrown when the
+        /// <paramref name="creationOptions"/> argument or the <paramref name="continuationOptions"/>
+        /// argumentspecifies an invalid value.
+        /// </exception>
+        /// <remarks>
+        /// With this constructor, the
+        /// <see cref="TaskCreationOptions"/> property is initialized to <paramref name="creationOptions"/>,
+        /// the
+        /// <see cref="TaskContinuationOptions"/> property is initialized to <paramref
+        /// name="continuationOptions"/>, and the <see
+        /// cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see> property is initialized to
+        /// <paramref name="scheduler"/>, unless it's null, in which case the property is initialized to the
+        /// current scheduler (see <see
+        /// cref="System.Threading.Tasks.TaskScheduler.Current">TaskScheduler.Current</see>).
+        /// </remarks>
+        public TaskFactory(CancellationToken cancellationToken, TaskCreationOptions creationOptions, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
+        {
+            TaskFactory.CheckMultiTaskContinuationOptions(continuationOptions);
+            TaskFactory.CheckCreationOptions(creationOptions);
+
+            m_defaultCancellationToken = cancellationToken;
+            m_defaultScheduler = scheduler;
+            m_defaultCreationOptions = creationOptions;
+            m_defaultContinuationOptions = continuationOptions;
+        }
+
+        /* Properties */
+
+        /// <summary>
+        /// Gets the default <see cref="System.Threading.CancellationToken">CancellationToken</see> of this
+        /// TaskFactory.
+        /// </summary>
+        /// <remarks>
+        /// This property returns the default <see cref="CancellationToken"/> that will be assigned to all 
+        /// tasks created by this factory unless another CancellationToken value is explicitly specified 
+        /// during the call to the factory methods.
+        /// </remarks>
+        public CancellationToken CancellationToken { get { return m_defaultCancellationToken; } }
+
+        /// <summary>
+        /// Gets the <see cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see> of this
+        /// TaskFactory{TResult}.
+        /// </summary>
+        /// <remarks>
+        /// This property returns the default scheduler for this factory.  It will be used to schedule all 
+        /// tasks unless another scheduler is explicitly specified during calls to this factory's methods.  
+        /// If null, <see cref="System.Threading.Tasks.TaskScheduler.Current">TaskScheduler.Current</see> 
+        /// will be used.
+        /// </remarks>
+        public TaskScheduler Scheduler { get { return m_defaultScheduler; } }
+
+        /// <summary>
+        /// Gets the <see cref="System.Threading.Tasks.TaskCreationOptions">TaskCreationOptions
+        /// </see> value of this TaskFactory{TResult}.
+        /// </summary>
+        /// <remarks>
+        /// This property returns the default creation options for this factory.  They will be used to create all 
+        /// tasks unless other options are explicitly specified during calls to this factory's methods.
+        /// </remarks>
+        public TaskCreationOptions CreationOptions { get { return m_defaultCreationOptions; } }
+
+        /// <summary>
+        /// Gets the <see cref="System.Threading.Tasks.TaskCreationOptions">TaskContinuationOptions
+        /// </see> value of this TaskFactory{TResult}.
+        /// </summary>
+        /// <remarks>
+        /// This property returns the default continuation options for this factory.  They will be used to create 
+        /// all continuation tasks unless other options are explicitly specified during calls to this factory's methods.
+        /// </remarks>
+        public TaskContinuationOptions ContinuationOptions { get { return m_defaultContinuationOptions; } }
+
+
+        /* StartNew */
+
+        /// <summary>
+        /// Creates and starts a <see cref="T:System.Threading.Tasks.Task{TResult}"/>.
+        /// </summary>
+        /// <param name="function">A function delegate that returns the future result to be available through
+        /// the <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</param>
+        /// <returns>The started <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref
+        /// name="function"/>
+        /// argument is null.</exception>
+        /// <remarks>
+        /// Calling StartNew is functionally equivalent to creating a <see cref="Task{TResult}"/> using one
+        /// of its constructors and then calling
+        /// <see cref="System.Threading.Tasks.Task.Start()">Start</see> to schedule it for execution.
+        /// However, unless creation and scheduling must be separated, StartNew is the recommended approach
+        /// for both simplicity and performance.
+        /// </remarks>
+        public Task<TResult> StartNew(Func<TResult> function)
+        {
+            Task currTask = Task.InternalCurrent;
+            return Task<TResult>.StartNew(currTask, function, m_defaultCancellationToken,
+                m_defaultCreationOptions, InternalTaskOptions.None, GetDefaultScheduler(currTask));
+        }
+
+        /// <summary>
+        /// Creates and starts a <see cref="T:System.Threading.Tasks.Task{TResult}"/>.
+        /// </summary>
+        /// <param name="function">A function delegate that returns the future result to be available through
+        /// the <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</param>
+        /// <param name="cancellationToken">The <see cref="CancellationToken"/> that will be assigned to the new task.</param>
+        /// <returns>The started <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref
+        /// name="function"/>
+        /// argument is null.</exception>
+        /// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
+        /// has already been disposed.
+        /// </exception>
+        /// <remarks>
+        /// Calling StartNew is functionally equivalent to creating a <see cref="Task{TResult}"/> using one
+        /// of its constructors and then calling
+        /// <see cref="System.Threading.Tasks.Task.Start()">Start</see> to schedule it for execution.
+        /// However, unless creation and scheduling must be separated, StartNew is the recommended approach
+        /// for both simplicity and performance.
+        /// </remarks>
+        public Task<TResult> StartNew(Func<TResult> function, CancellationToken cancellationToken)
+        {
+            Task currTask = Task.InternalCurrent;
+            return Task<TResult>.StartNew(currTask, function, cancellationToken,
+                m_defaultCreationOptions, InternalTaskOptions.None, GetDefaultScheduler(currTask));
+        }
+
+        /// <summary>
+        /// Creates and starts a <see cref="T:System.Threading.Tasks.Task{TResult}"/>.
+        /// </summary>
+        /// <param name="function">A function delegate that returns the future result to be available through
+        /// the <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</param>
+        /// <param name="creationOptions">A TaskCreationOptions value that controls the behavior of the
+        /// created
+        /// <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</param>
+        /// <returns>The started <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref
+        /// name="function"/>
+        /// argument is null.</exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">The exception that is thrown when the
+        /// <paramref name="creationOptions"/> argument specifies an invalid TaskCreationOptions
+        /// value.</exception>
+        /// <remarks>
+        /// Calling StartNew is functionally equivalent to creating a <see cref="Task{TResult}"/> using one
+        /// of its constructors and then calling
+        /// <see cref="System.Threading.Tasks.Task.Start()">Start</see> to schedule it for execution.
+        /// However, unless creation and scheduling must be separated, StartNew is the recommended approach
+        /// for both simplicity and performance.
+        /// </remarks>
+        public Task<TResult> StartNew(Func<TResult> function, TaskCreationOptions creationOptions)
+        {
+            Task currTask = Task.InternalCurrent;
+            return Task<TResult>.StartNew(currTask, function, m_defaultCancellationToken,
+                creationOptions, InternalTaskOptions.None, GetDefaultScheduler(currTask));
+        }
+
+        /// <summary>
+        /// Creates and starts a <see cref="T:System.Threading.Tasks.Task{TResult}"/>.
+        /// </summary>
+        /// <param name="function">A function delegate that returns the future result to be available through
+        /// the <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</param>
+        /// <param name="creationOptions">A TaskCreationOptions value that controls the behavior of the
+        /// created
+        /// <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</param>
+        /// <param name="cancellationToken">The <see cref="CancellationToken"/> that will be assigned to the new task.</param>
+        /// <param name="scheduler">The <see
+        /// cref="T:System.Threading.Tasks.TaskScheduler">TaskScheduler</see>
+        /// that is used to schedule the created <see cref="T:System.Threading.Tasks.Task{TResult}">
+        /// Task{TResult}</see>.</param>
+        /// <returns>The started <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref
+        /// name="function"/>
+        /// argument is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref
+        /// name="scheduler"/>
+        /// argument is null.</exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">The exception that is thrown when the
+        /// <paramref name="creationOptions"/> argument specifies an invalid TaskCreationOptions
+        /// value.</exception>
+        /// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
+        /// has already been disposed.
+        /// </exception>
+        /// <remarks>
+        /// Calling StartNew is functionally equivalent to creating a <see cref="Task{TResult}"/> using one
+        /// of its constructors and then calling
+        /// <see cref="System.Threading.Tasks.Task.Start()">Start</see> to schedule it for execution.
+        /// However, unless creation and scheduling must be separated, StartNew is the recommended approach
+        /// for both simplicity and performance.
+        /// </remarks>
+        public Task<TResult> StartNew(Func<TResult> function, CancellationToken cancellationToken, TaskCreationOptions creationOptions, TaskScheduler scheduler)
+        {
+            return Task<TResult>.StartNew(
+                Task.InternalCurrentIfAttached(creationOptions), function, cancellationToken,
+                creationOptions, InternalTaskOptions.None, scheduler);
+        }
+
+        /// <summary>
+        /// Creates and starts a <see cref="T:System.Threading.Tasks.Task{TResult}"/>.
+        /// </summary>
+        /// <param name="function">A function delegate that returns the future result to be available through
+        /// the <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</param>
+        /// <param name="state">An object containing data to be used by the <paramref name="function"/>
+        /// delegate.</param>
+        /// <returns>The started <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref
+        /// name="function"/>
+        /// argument is null.</exception>
+        /// <remarks>
+        /// Calling StartNew is functionally equivalent to creating a <see cref="Task{TResult}"/> using one
+        /// of its constructors and then calling
+        /// <see cref="System.Threading.Tasks.Task.Start()">Start</see> to schedule it for execution.
+        /// However, unless creation and scheduling must be separated, StartNew is the recommended approach
+        /// for both simplicity and performance.
+        /// </remarks>
+        public Task<TResult> StartNew(Func<object, TResult> function, object state)
+        {
+            Task currTask = Task.InternalCurrent;
+            return Task<TResult>.StartNew(currTask, function, state, m_defaultCancellationToken,
+                m_defaultCreationOptions, InternalTaskOptions.None, GetDefaultScheduler(currTask));
+        }
+
+        /// <summary>
+        /// Creates and starts a <see cref="T:System.Threading.Tasks.Task{TResult}"/>.
+        /// </summary>
+        /// <param name="function">A function delegate that returns the future result to be available through
+        /// the <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</param>
+        /// <param name="state">An object containing data to be used by the <paramref name="function"/>
+        /// delegate.</param>
+        /// <param name="cancellationToken">The <see cref="CancellationToken"/> that will be assigned to the new task.</param>
+        /// <returns>The started <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref
+        /// name="function"/>
+        /// argument is null.</exception>
+        /// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
+        /// has already been disposed.
+        /// </exception>
+        /// <remarks>
+        /// Calling StartNew is functionally equivalent to creating a <see cref="Task{TResult}"/> using one
+        /// of its constructors and then calling
+        /// <see cref="System.Threading.Tasks.Task.Start()">Start</see> to schedule it for execution.
+        /// However, unless creation and scheduling must be separated, StartNew is the recommended approach
+        /// for both simplicity and performance.
+        /// </remarks>
+        public Task<TResult> StartNew(Func<object, TResult> function, object state, CancellationToken cancellationToken)
+        {
+            Task currTask = Task.InternalCurrent;
+            return Task<TResult>.StartNew(currTask, function, state, cancellationToken,
+                m_defaultCreationOptions, InternalTaskOptions.None, GetDefaultScheduler(currTask));
+        }
+
+        /// <summary>
+        /// Creates and starts a <see cref="T:System.Threading.Tasks.Task{TResult}"/>.
+        /// </summary>
+        /// <param name="function">A function delegate that returns the future result to be available through
+        /// the <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</param>
+        /// <param name="state">An object containing data to be used by the <paramref name="function"/>
+        /// delegate.</param>
+        /// <param name="creationOptions">A TaskCreationOptions value that controls the behavior of the
+        /// created
+        /// <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</param>
+        /// <returns>The started <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref
+        /// name="function"/>
+        /// argument is null.</exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">The exception that is thrown when the
+        /// <paramref name="creationOptions"/> argument specifies an invalid TaskCreationOptions
+        /// value.</exception>
+        /// <remarks>
+        /// Calling StartNew is functionally equivalent to creating a <see cref="Task{TResult}"/> using one
+        /// of its constructors and then calling
+        /// <see cref="System.Threading.Tasks.Task.Start()">Start</see> to schedule it for execution.
+        /// However, unless creation and scheduling must be separated, StartNew is the recommended approach
+        /// for both simplicity and performance.
+        /// </remarks>
+        public Task<TResult> StartNew(Func<object, TResult> function, object state, TaskCreationOptions creationOptions)
+        {
+            Task currTask = Task.InternalCurrent;
+            return Task<TResult>.StartNew(currTask, function, state, m_defaultCancellationToken,
+                creationOptions, InternalTaskOptions.None, GetDefaultScheduler(currTask));
+        }
+
+        /// <summary>
+        /// Creates and starts a <see cref="T:System.Threading.Tasks.Task{TResult}"/>.
+        /// </summary>
+        /// <param name="function">A function delegate that returns the future result to be available through
+        /// the <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</param>
+        /// <param name="state">An object containing data to be used by the <paramref name="function"/>
+        /// delegate.</param>
+        /// <param name="cancellationToken">The <see cref="CancellationToken"/> that will be assigned to the new task.</param>
+        /// <param name="creationOptions">A TaskCreationOptions value that controls the behavior of the
+        /// created
+        /// <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</param>
+        /// <param name="scheduler">The <see
+        /// cref="T:System.Threading.Tasks.TaskScheduler">TaskScheduler</see>
+        /// that is used to schedule the created <see cref="T:System.Threading.Tasks.Task{TResult}">
+        /// Task{TResult}</see>.</param>
+        /// <returns>The started <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref
+        /// name="function"/>
+        /// argument is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref
+        /// name="scheduler"/>
+        /// argument is null.</exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">The exception that is thrown when the
+        /// <paramref name="creationOptions"/> argument specifies an invalid TaskCreationOptions
+        /// value.</exception>
+        /// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
+        /// has already been disposed.
+        /// </exception>
+        /// <remarks>
+        /// Calling StartNew is functionally equivalent to creating a <see cref="Task{TResult}"/> using one
+        /// of its constructors and then calling
+        /// <see cref="System.Threading.Tasks.Task.Start()">Start</see> to schedule it for execution.
+        /// However, unless creation and scheduling must be separated, StartNew is the recommended approach
+        /// for both simplicity and performance.
+        /// </remarks>
+        public Task<TResult> StartNew(Func<object, TResult> function, object state, CancellationToken cancellationToken, TaskCreationOptions creationOptions, TaskScheduler scheduler)
+        {
+            return Task<TResult>.StartNew(Task.InternalCurrentIfAttached(creationOptions), function, state, cancellationToken,
+                creationOptions, InternalTaskOptions.None, scheduler);
+        }
+
+        //
+        // APM Factory methods
+        //
+
+        // Common core logic for FromAsync calls.  This minimizes the chance of "drift" between overload implementations.
+        private static void FromAsyncCoreLogic(
+            IAsyncResult iar,
+            Func<IAsyncResult, TResult> endFunction,
+            Action<IAsyncResult> endAction,
+            Task<TResult> promise,
+            bool requiresSynchronization)
+        {
+            Debug.Assert((endFunction != null) != (endAction != null), "Expected exactly one of endFunction/endAction to be non-null");
+
+            Exception ex = null;
+            OperationCanceledException oce = null;
+            TResult result = default;
+
+            try
+            {
+                if (endFunction != null)
+                {
+                    result = endFunction(iar);
+                }
+                else
+                {
+                    endAction(iar);
+                }
+            }
+            catch (OperationCanceledException _oce) { oce = _oce; }
+            catch (Exception e) { ex = e; }
+            finally
+            {
+                if (oce != null)
+                {
+                    promise.TrySetCanceled(oce.CancellationToken, oce);
+                }
+                else if (ex != null)
+                {
+                    bool bWonSetException = promise.TrySetException(ex);
+                    //if (bWonSetException && ex is ThreadAbortException)
+                    //{
+                    //    promise.m_contingentProperties.m_exceptionsHolder.MarkAsHandled(false);
+                    //}
+                }
+                else
+                {
+                    if (DebuggerSupport.LoggingOn)
+                        DebuggerSupport.TraceOperationCompletion(CausalityTraceLevel.Required, promise, AsyncStatus.Completed);
+                    DebuggerSupport.RemoveFromActiveTasks(promise);
+
+                    if (requiresSynchronization)
+                    {
+                        promise.TrySetResult(result);
+                    }
+                    else
+                    {
+                        promise.DangerousSetResult(result);
+                    }
+                }
+            }
+        }
+
+        /// <summary>
+        /// Creates a <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see> that executes an end
+        /// method function when a specified <see cref="T:System.IAsyncResult">IAsyncResult</see> completes.
+        /// </summary>
+        /// <param name="asyncResult">The IAsyncResult whose completion should trigger the processing of the
+        /// <paramref name="endMethod"/>.</param>
+        /// <param name="endMethod">The function delegate that processes the completed <paramref
+        /// name="asyncResult"/>.</param>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="asyncResult"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="endMethod"/> argument is null.</exception>
+        /// <returns>A <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see> that represents the
+        /// asynchronous operation.</returns>
+        public Task<TResult> FromAsync(IAsyncResult asyncResult, Func<IAsyncResult, TResult> endMethod)
+        {
+            return FromAsyncImpl(asyncResult, endMethod, null, m_defaultCreationOptions, DefaultScheduler);
+        }
+
+        /// <summary>
+        /// Creates a <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see> that executes an end
+        /// method function when a specified <see cref="T:System.IAsyncResult">IAsyncResult</see> completes.
+        /// </summary>
+        /// <param name="asyncResult">The IAsyncResult whose completion should trigger the processing of the
+        /// <paramref name="endMethod"/>.</param>
+        /// <param name="endMethod">The function delegate that processes the completed <paramref
+        /// name="asyncResult"/>.</param>
+        /// <param name="creationOptions">The TaskCreationOptions value that controls the behavior of the
+        /// created <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>.</param>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="asyncResult"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="endMethod"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">The exception that is thrown when the
+        /// <paramref name="creationOptions"/> argument specifies an invalid TaskCreationOptions
+        /// value.</exception>
+        /// <returns>A <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see> that represents the
+        /// asynchronous operation.</returns>
+        public Task<TResult> FromAsync(
+            IAsyncResult asyncResult,
+            Func<IAsyncResult, TResult> endMethod,
+            TaskCreationOptions creationOptions)
+        {
+            return FromAsyncImpl(asyncResult, endMethod, null, creationOptions, DefaultScheduler);
+        }
+
+
+
+        /// <summary>
+        /// Creates a <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see> that executes an end
+        /// method function when a specified <see cref="T:System.IAsyncResult">IAsyncResult</see> completes.
+        /// </summary>
+        /// <param name="asyncResult">The IAsyncResult whose completion should trigger the processing of the
+        /// <paramref name="endMethod"/>.</param>
+        /// <param name="endMethod">The function delegate that processes the completed <paramref
+        /// name="asyncResult"/>.</param>
+        /// <param name="scheduler">The <see cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see>
+        /// that is used to schedule the task that executes the end method.</param>
+        /// <param name="creationOptions">The TaskCreationOptions value that controls the behavior of the
+        /// created <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>.</param>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="asyncResult"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="endMethod"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="scheduler"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">The exception that is thrown when the
+        /// <paramref name="creationOptions"/> argument specifies an invalid TaskCreationOptions
+        /// value.</exception>
+        /// <returns>A <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see> that represents the
+        /// asynchronous operation.</returns>
+        public Task<TResult> FromAsync(
+            IAsyncResult asyncResult,
+            Func<IAsyncResult, TResult> endMethod,
+            TaskCreationOptions creationOptions,
+            TaskScheduler scheduler)
+        {
+            return FromAsyncImpl(asyncResult, endMethod, null, creationOptions, scheduler);
+        }
+
+        // We need this logic broken out into a static method so that the similar TaskFactory.FromAsync()
+        // method can access the logic w/o declaring a TaskFactory<TResult> instance.
+        internal static Task<TResult> FromAsyncImpl(
+            IAsyncResult asyncResult,
+            Func<IAsyncResult, TResult> endFunction,
+            Action<IAsyncResult> endAction,
+            TaskCreationOptions creationOptions,
+            TaskScheduler scheduler)
+        {
+            if (asyncResult == null)
+                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.asyncResult);
+
+            if (endFunction == null && endAction == null)
+                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.endMethod);
+
+            Debug.Assert((endFunction != null) != (endAction != null), "Both endFunction and endAction were non-null");
+
+            if (scheduler == null)
+                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler);
+
+            TaskFactory.CheckFromAsyncOptions(creationOptions, false);
+
+            Task<TResult> promise = new Task<TResult>((object)null, creationOptions);
+
+            // Just specify this task as detached. No matter what happens, we want endMethod 
+            // to be called -- even if the parent is canceled.  So we don't want to flow 
+            // RespectParentCancellation.
+            Task t = new Task(new Action<object>(delegate
+            {
+                FromAsyncCoreLogic(asyncResult, endFunction, endAction, promise, requiresSynchronization: true);
+            }),
+                (object)null, null,
+                default, TaskCreationOptions.None, InternalTaskOptions.None, null);
+
+            if (asyncResult.IsCompleted)
+            {
+                try { t.InternalRunSynchronously(scheduler, waitForCompletion: false); }
+                catch (Exception e) { promise.TrySetException(e); } // catch and log any scheduler exceptions
+            }
+            else
+            {
+                ThreadPool.RegisterWaitForSingleObject(
+                    asyncResult.AsyncWaitHandle,
+                    delegate
+                    {
+                        try { t.InternalRunSynchronously(scheduler, waitForCompletion: false); }
+                        catch (Exception e) { promise.TrySetException(e); } // catch and log any scheduler exceptions
+                    },
+                    null,
+                    Timeout.Infinite,
+                    true);
+            }
+
+            return promise;
+        }
+
+        /// <summary>
+        /// Creates a <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see> that represents a pair of
+        /// begin and end methods that conform to the Asynchronous Programming Model pattern.
+        /// </summary>
+        /// <param name="beginMethod">The delegate that begins the asynchronous operation.</param>
+        /// <param name="endMethod">The delegate that ends the asynchronous operation.</param>
+        /// <param name="state">An object containing data to be used by the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="beginMethod"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="endMethod"/> argument is null.</exception>
+        /// <returns>The created <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see> that
+        /// represents the asynchronous operation.</returns>
+        /// <remarks>
+        /// This method throws any exceptions thrown by the <paramref name="beginMethod"/>.
+        /// </remarks>
+        public Task<TResult> FromAsync(
+            Func<AsyncCallback, object, IAsyncResult> beginMethod,
+            Func<IAsyncResult, TResult> endMethod, object state)
+        {
+            return FromAsyncImpl(beginMethod, endMethod, null, state, m_defaultCreationOptions);
+        }
+
+        /// <summary>
+        /// Creates a <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see> that represents a pair of
+        /// begin and end methods that conform to the Asynchronous Programming Model pattern.
+        /// </summary>
+        /// <param name="beginMethod">The delegate that begins the asynchronous operation.</param>
+        /// <param name="endMethod">The delegate that ends the asynchronous operation.</param>
+        /// <param name="creationOptions">The TaskCreationOptions value that controls the behavior of the
+        /// created <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>.</param>
+        /// <param name="state">An object containing data to be used by the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="beginMethod"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="endMethod"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">The exception that is thrown when the
+        /// <paramref name="creationOptions"/> argument specifies an invalid TaskCreationOptions
+        /// value.</exception>
+        /// <returns>The created <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see> that
+        /// represents the asynchronous operation.</returns>
+        /// <remarks>
+        /// This method throws any exceptions thrown by the <paramref name="beginMethod"/>.
+        /// </remarks>
+        public Task<TResult> FromAsync(
+            Func<AsyncCallback, object, IAsyncResult> beginMethod,
+            Func<IAsyncResult, TResult> endMethod, object state, TaskCreationOptions creationOptions)
+        {
+            return FromAsyncImpl(beginMethod, endMethod, null, state, creationOptions);
+        }
+
+        // We need this logic broken out into a static method so that the similar TaskFactory.FromAsync()
+        // method can access the logic w/o declaring a TaskFactory<TResult> instance.
+        internal static Task<TResult> FromAsyncImpl(Func<AsyncCallback, object, IAsyncResult> beginMethod,
+            Func<IAsyncResult, TResult> endFunction, Action<IAsyncResult> endAction,
+            object state, TaskCreationOptions creationOptions)
+        {
+            if (beginMethod == null)
+                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.beginMethod);
+
+            if (endFunction == null && endAction == null)
+                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.endMethod);
+
+            Debug.Assert((endFunction != null) != (endAction != null), "Both endFunction and endAction were non-null");
+
+            TaskFactory.CheckFromAsyncOptions(creationOptions, true);
+
+            Task<TResult> promise = new Task<TResult>(state, creationOptions);
+
+            if (DebuggerSupport.LoggingOn)
+                DebuggerSupport.TraceOperationCreation(CausalityTraceLevel.Required, promise, "TaskFactory.FromAsync: " + beginMethod, 0);
+            DebuggerSupport.AddToActiveTasks(promise);
+
+            try
+            {
+                var asyncResult = beginMethod(iar =>
+                {
+                    if (!iar.CompletedSynchronously)
+                        FromAsyncCoreLogic(iar, endFunction, endAction, promise, requiresSynchronization: true);
+                }, state);
+                if (asyncResult.CompletedSynchronously)
+                {
+                    Debug.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed.");
+                    FromAsyncCoreLogic(asyncResult, endFunction, endAction, promise, requiresSynchronization: false);
+                }
+            }
+            catch
+            {
+                if (DebuggerSupport.LoggingOn)
+                    DebuggerSupport.TraceOperationCompletion(CausalityTraceLevel.Required, promise, AsyncStatus.Error);
+                DebuggerSupport.RemoveFromActiveTasks(promise);
+
+                // Make sure we don't leave promise "dangling".
+                promise.TrySetResult(default);
+                throw;
+            }
+
+            return promise;
+        }
+
+        /// <summary>
+        /// Creates a <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see> that represents a pair of
+        /// begin and end methods that conform to the Asynchronous Programming Model pattern.
+        /// </summary>
+        /// <typeparam name="TArg1">The type of the first argument passed to the <paramref
+        /// name="beginMethod"/> delegate.</typeparam>
+        /// <param name="beginMethod">The delegate that begins the asynchronous operation.</param>
+        /// <param name="endMethod">The delegate that ends the asynchronous operation.</param>
+        /// <param name="arg1">The first argument passed to the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <param name="state">An object containing data to be used by the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="beginMethod"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="endMethod"/> argument is null.</exception>
+        /// <returns>The created <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see> that
+        /// represents the asynchronous operation.</returns>
+        /// <remarks>
+        /// This method throws any exceptions thrown by the <paramref name="beginMethod"/>.
+        /// </remarks>
+        public Task<TResult> FromAsync<TArg1>(
+            Func<TArg1, AsyncCallback, object, IAsyncResult> beginMethod,
+            Func<IAsyncResult, TResult> endMethod,
+            TArg1 arg1, object state)
+        {
+            return FromAsyncImpl(beginMethod, endMethod, null, arg1, state, m_defaultCreationOptions);
+        }
+
+        /// <summary>
+        /// Creates a <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see> that represents a pair of
+        /// begin and end methods that conform to the Asynchronous Programming Model pattern.
+        /// </summary>
+        /// <typeparam name="TArg1">The type of the first argument passed to the <paramref
+        /// name="beginMethod"/> delegate.</typeparam>
+        /// <param name="beginMethod">The delegate that begins the asynchronous operation.</param>
+        /// <param name="endMethod">The delegate that ends the asynchronous operation.</param>
+        /// <param name="arg1">The first argument passed to the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <param name="creationOptions">The TaskCreationOptions value that controls the behavior of the
+        /// created <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>.</param>
+        /// <param name="state">An object containing data to be used by the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="beginMethod"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="endMethod"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">The exception that is thrown when the
+        /// <paramref name="creationOptions"/> argument specifies an invalid TaskCreationOptions
+        /// value.</exception>
+        /// <returns>The created <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see> that
+        /// represents the asynchronous operation.</returns>
+        /// <remarks>
+        /// This method throws any exceptions thrown by the <paramref name="beginMethod"/>.
+        /// </remarks>
+        public Task<TResult> FromAsync<TArg1>(
+            Func<TArg1, AsyncCallback, object, IAsyncResult> beginMethod,
+            Func<IAsyncResult, TResult> endMethod,
+            TArg1 arg1, object state, TaskCreationOptions creationOptions)
+        {
+            return FromAsyncImpl(beginMethod, endMethod, null, arg1, state, creationOptions);
+        }
+
+        // We need this logic broken out into a static method so that the similar TaskFactory.FromAsync()
+        // method can access the logic w/o declaring a TaskFactory<TResult> instance.
+        internal static Task<TResult> FromAsyncImpl<TArg1>(Func<TArg1, AsyncCallback, object, IAsyncResult> beginMethod,
+            Func<IAsyncResult, TResult> endFunction, Action<IAsyncResult> endAction,
+            TArg1 arg1, object state, TaskCreationOptions creationOptions)
+        {
+            if (beginMethod == null)
+                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.beginMethod);
+
+            if (endFunction == null && endAction == null)
+                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.endFunction);
+
+            Debug.Assert((endFunction != null) != (endAction != null), "Both endFunction and endAction were non-null");
+
+            TaskFactory.CheckFromAsyncOptions(creationOptions, true);
+
+            Task<TResult> promise = new Task<TResult>(state, creationOptions);
+
+            if (DebuggerSupport.LoggingOn)
+                DebuggerSupport.TraceOperationCreation(CausalityTraceLevel.Required, promise, "TaskFactory.FromAsync: " + beginMethod, 0);
+            DebuggerSupport.AddToActiveTasks(promise);
+
+            try
+            {
+                //if we don't require synchronization, a faster set result path is taken
+                var asyncResult = beginMethod(arg1, iar =>
+                {
+                    if (!iar.CompletedSynchronously)
+                        FromAsyncCoreLogic(iar, endFunction, endAction, promise, requiresSynchronization: true);
+                }, state);
+                if (asyncResult.CompletedSynchronously)
+                {
+                    Debug.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed.");
+                    FromAsyncCoreLogic(asyncResult, endFunction, endAction, promise, requiresSynchronization: false);
+                }
+            }
+            catch
+            {
+                if (DebuggerSupport.LoggingOn)
+                    DebuggerSupport.TraceOperationCompletion(CausalityTraceLevel.Required, promise, AsyncStatus.Error);
+                DebuggerSupport.RemoveFromActiveTasks(promise);
+
+                // Make sure we don't leave promise "dangling".
+                promise.TrySetResult(default(TResult));
+                throw;
+            }
+
+            return promise;
+        }
+
+        /// <summary>
+        /// Creates a <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see> that represents a pair of
+        /// begin and end methods that conform to the Asynchronous Programming Model pattern.
+        /// </summary>
+        /// <typeparam name="TArg1">The type of the first argument passed to the <paramref
+        /// name="beginMethod"/> delegate.</typeparam>
+        /// <typeparam name="TArg2">The type of the second argument passed to <paramref name="beginMethod"/>
+        /// delegate.</typeparam>
+        /// <param name="beginMethod">The delegate that begins the asynchronous operation.</param>
+        /// <param name="endMethod">The delegate that ends the asynchronous operation.</param>
+        /// <param name="arg1">The first argument passed to the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <param name="arg2">The second argument passed to the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <param name="state">An object containing data to be used by the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="beginMethod"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="endMethod"/> argument is null.</exception>
+        /// <returns>The created <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see> that
+        /// represents the asynchronous operation.</returns>
+        /// <remarks>
+        /// This method throws any exceptions thrown by the <paramref name="beginMethod"/>.
+        /// </remarks>
+        public Task<TResult> FromAsync<TArg1, TArg2>(
+            Func<TArg1, TArg2, AsyncCallback, object, IAsyncResult> beginMethod,
+            Func<IAsyncResult, TResult> endMethod,
+            TArg1 arg1, TArg2 arg2, object state)
+        {
+            return FromAsyncImpl(beginMethod, endMethod, null, arg1, arg2, state, m_defaultCreationOptions);
+        }
+
+        /// <summary>
+        /// Creates a <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see> that represents a pair of
+        /// begin and end methods that conform to the Asynchronous Programming Model pattern.
+        /// </summary>
+        /// <typeparam name="TArg1">The type of the first argument passed to the <paramref
+        /// name="beginMethod"/> delegate.</typeparam>
+        /// <typeparam name="TArg2">The type of the second argument passed to <paramref name="beginMethod"/>
+        /// delegate.</typeparam>
+        /// <param name="beginMethod">The delegate that begins the asynchronous operation.</param>
+        /// <param name="endMethod">The delegate that ends the asynchronous operation.</param>
+        /// <param name="arg1">The first argument passed to the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <param name="arg2">The second argument passed to the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <param name="creationOptions">The TaskCreationOptions value that controls the behavior of the
+        /// created <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>.</param>
+        /// <param name="state">An object containing data to be used by the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="beginMethod"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="endMethod"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">The exception that is thrown when the
+        /// <paramref name="creationOptions"/> argument specifies an invalid TaskCreationOptions
+        /// value.</exception>
+        /// <returns>The created <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see> that
+        /// represents the asynchronous operation.</returns>
+        /// <remarks>
+        /// This method throws any exceptions thrown by the <paramref name="beginMethod"/>.
+        /// </remarks>
+        public Task<TResult> FromAsync<TArg1, TArg2>(
+            Func<TArg1, TArg2, AsyncCallback, object, IAsyncResult> beginMethod,
+            Func<IAsyncResult, TResult> endMethod,
+            TArg1 arg1, TArg2 arg2, object state, TaskCreationOptions creationOptions)
+        {
+            return FromAsyncImpl(beginMethod, endMethod, null, arg1, arg2, state, creationOptions);
+        }
+
+        // We need this logic broken out into a static method so that the similar TaskFactory.FromAsync()
+        // method can access the logic w/o declaring a TaskFactory<TResult> instance.
+        internal static Task<TResult> FromAsyncImpl<TArg1, TArg2>(Func<TArg1, TArg2, AsyncCallback, object, IAsyncResult> beginMethod,
+            Func<IAsyncResult, TResult> endFunction, Action<IAsyncResult> endAction,
+            TArg1 arg1, TArg2 arg2, object state, TaskCreationOptions creationOptions)
+        {
+            if (beginMethod == null)
+                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.beginMethod);
+
+            if (endFunction == null && endAction == null)
+                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.endMethod);
+
+            Debug.Assert((endFunction != null) != (endAction != null), "Both endFunction and endAction were non-null");
+
+            TaskFactory.CheckFromAsyncOptions(creationOptions, true);
+
+            Task<TResult> promise = new Task<TResult>(state, creationOptions);
+
+            if (DebuggerSupport.LoggingOn)
+                DebuggerSupport.TraceOperationCreation(CausalityTraceLevel.Required, promise, "TaskFactory.FromAsync: " + beginMethod, 0);
+            DebuggerSupport.AddToActiveTasks(promise);
+
+            try
+            {
+                //if we don't require synchronization, a faster set result path is taken
+                var asyncResult = beginMethod(arg1, arg2, iar =>
+                {
+                    if (!iar.CompletedSynchronously)
+                        FromAsyncCoreLogic(iar, endFunction, endAction, promise, requiresSynchronization: true);
+                }, state);
+                if (asyncResult.CompletedSynchronously)
+                {
+                    Debug.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed.");
+                    FromAsyncCoreLogic(asyncResult, endFunction, endAction, promise, requiresSynchronization: false);
+                }
+            }
+            catch
+            {
+                if (DebuggerSupport.LoggingOn)
+                    DebuggerSupport.TraceOperationCompletion(CausalityTraceLevel.Required, promise, AsyncStatus.Error);
+                DebuggerSupport.RemoveFromActiveTasks(promise);
+
+                // Make sure we don't leave promise "dangling".
+                promise.TrySetResult(default);
+                throw;
+            }
+
+            return promise;
+        }
+
+        /// <summary>
+        /// Creates a <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see> that represents a pair of
+        /// begin and end methods that conform to the Asynchronous Programming Model pattern.
+        /// </summary>
+        /// <typeparam name="TArg1">The type of the first argument passed to the <paramref
+        /// name="beginMethod"/> delegate.</typeparam>
+        /// <typeparam name="TArg2">The type of the second argument passed to <paramref name="beginMethod"/>
+        /// delegate.</typeparam>
+        /// <typeparam name="TArg3">The type of the third argument passed to <paramref name="beginMethod"/>
+        /// delegate.</typeparam>
+        /// <param name="beginMethod">The delegate that begins the asynchronous operation.</param>
+        /// <param name="endMethod">The delegate that ends the asynchronous operation.</param>
+        /// <param name="arg1">The first argument passed to the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <param name="arg2">The second argument passed to the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <param name="arg3">The third argument passed to the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <param name="state">An object containing data to be used by the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="beginMethod"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="endMethod"/> argument is null.</exception>
+        /// <returns>The created <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see> that
+        /// represents the asynchronous operation.</returns>
+        /// <remarks>
+        /// This method throws any exceptions thrown by the <paramref name="beginMethod"/>.
+        /// </remarks>
+        public Task<TResult> FromAsync<TArg1, TArg2, TArg3>(
+            Func<TArg1, TArg2, TArg3, AsyncCallback, object, IAsyncResult> beginMethod,
+            Func<IAsyncResult, TResult> endMethod,
+            TArg1 arg1, TArg2 arg2, TArg3 arg3, object state)
+        {
+            return FromAsyncImpl(beginMethod, endMethod, null, arg1, arg2, arg3, state, m_defaultCreationOptions);
+        }
+
+        /// <summary>
+        /// Creates a <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see> that represents a pair of
+        /// begin and end methods that conform to the Asynchronous Programming Model pattern.
+        /// </summary>
+        /// <typeparam name="TArg1">The type of the first argument passed to the <paramref
+        /// name="beginMethod"/> delegate.</typeparam>
+        /// <typeparam name="TArg2">The type of the second argument passed to <paramref name="beginMethod"/>
+        /// delegate.</typeparam>
+        /// <typeparam name="TArg3">The type of the third argument passed to <paramref name="beginMethod"/>
+        /// delegate.</typeparam>
+        /// <param name="beginMethod">The delegate that begins the asynchronous operation.</param>
+        /// <param name="endMethod">The delegate that ends the asynchronous operation.</param>
+        /// <param name="arg1">The first argument passed to the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <param name="arg2">The second argument passed to the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <param name="arg3">The third argument passed to the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <param name="creationOptions">The TaskCreationOptions value that controls the behavior of the
+        /// created <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>.</param>
+        /// <param name="state">An object containing data to be used by the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="beginMethod"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="endMethod"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">The exception that is thrown when the
+        /// <paramref name="creationOptions"/> argument specifies an invalid TaskCreationOptions
+        /// value.</exception>
+        /// <returns>The created <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see> that
+        /// represents the asynchronous operation.</returns>
+        /// <remarks>
+        /// This method throws any exceptions thrown by the <paramref name="beginMethod"/>.
+        /// </remarks>
+        public Task<TResult> FromAsync<TArg1, TArg2, TArg3>(
+            Func<TArg1, TArg2, TArg3, AsyncCallback, object, IAsyncResult> beginMethod,
+            Func<IAsyncResult, TResult> endMethod,
+            TArg1 arg1, TArg2 arg2, TArg3 arg3, object state, TaskCreationOptions creationOptions)
+        {
+            return FromAsyncImpl(beginMethod, endMethod, null, arg1, arg2, arg3, state, creationOptions);
+        }
+
+        // We need this logic broken out into a static method so that the similar TaskFactory.FromAsync()
+        // method can access the logic w/o declaring a TaskFactory<TResult> instance.
+        internal static Task<TResult> FromAsyncImpl<TArg1, TArg2, TArg3>(Func<TArg1, TArg2, TArg3, AsyncCallback, object, IAsyncResult> beginMethod,
+            Func<IAsyncResult, TResult> endFunction, Action<IAsyncResult> endAction,
+            TArg1 arg1, TArg2 arg2, TArg3 arg3, object state, TaskCreationOptions creationOptions)
+        {
+            if (beginMethod == null)
+                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.beginMethod);
+
+            if (endFunction == null && endAction == null)
+                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.endMethod);
+
+            Debug.Assert((endFunction != null) != (endAction != null), "Both endFunction and endAction were non-null");
+
+            TaskFactory.CheckFromAsyncOptions(creationOptions, true);
+
+            Task<TResult> promise = new Task<TResult>(state, creationOptions);
+
+            if (DebuggerSupport.LoggingOn)
+                DebuggerSupport.TraceOperationCreation(CausalityTraceLevel.Required, promise, "TaskFactory.FromAsync: " + beginMethod, 0);
+            DebuggerSupport.AddToActiveTasks(promise);
+
+            try
+            {
+                //if we don't require synchronization, a faster set result path is taken
+                var asyncResult = beginMethod(arg1, arg2, arg3, iar =>
+                {
+                    if (!iar.CompletedSynchronously)
+                        FromAsyncCoreLogic(iar, endFunction, endAction, promise, requiresSynchronization: true);
+                }, state);
+                if (asyncResult.CompletedSynchronously)
+                {
+                    Debug.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed.");
+                    FromAsyncCoreLogic(asyncResult, endFunction, endAction, promise, requiresSynchronization: false);
+                }
+            }
+            catch
+            {
+                if (DebuggerSupport.LoggingOn)
+                    DebuggerSupport.TraceOperationCompletion(CausalityTraceLevel.Required, promise, AsyncStatus.Error);
+                DebuggerSupport.RemoveFromActiveTasks(promise);
+
+                // Make sure we don't leave the promise "dangling".
+                promise.TrySetResult(default);
+                throw;
+            }
+
+            return promise;
+        }
+
+        /// <summary>
+        /// Special internal-only FromAsync support used by System.IO to wrap
+        /// APM implementations with minimal overhead, avoiding unnecessary closure
+        /// and delegate allocations.
+        /// </summary>
+        /// <typeparam name="TInstance">Specifies the type of the instance on which the APM implementation lives.</typeparam>
+        /// <typeparam name="TArgs">Specifies the type containing the arguments.</typeparam>
+        /// <param name="thisRef">The instance from which the begin and end methods are invoked.</param>
+        /// <param name="beginMethod">The begin method.</param>
+        /// <param name="endMethod">The end method.</param>
+        /// <param name="args">The arguments.</param>
+        /// <returns>A task representing the asynchronous operation.</returns>
+        internal static Task<TResult> FromAsyncTrim<TInstance, TArgs>(
+            TInstance thisRef, TArgs args,
+            Func<TInstance, TArgs, AsyncCallback, object, IAsyncResult> beginMethod,
+            Func<TInstance, IAsyncResult, TResult> endMethod)
+            where TInstance : class
+        {
+            // Validate arguments, but only with asserts, as this is an internal only implementation.
+            Debug.Assert(thisRef != null, "Expected a non-null thisRef");
+            Debug.Assert(beginMethod != null, "Expected a non-null beginMethod");
+            Debug.Assert(endMethod != null, "Expected a non-null endMethod");
+
+            // Create the promise and start the operation.
+            // No try/catch is necessary here as we want exceptions to bubble out, and because
+            // the task doesn't have AttachedToParent set on it, there's no need to complete it in
+            // case of an exception occurring... we can just let it go unresolved.
+            var promise = new FromAsyncTrimPromise<TInstance>(thisRef, endMethod);
+            var asyncResult = beginMethod(thisRef, args, FromAsyncTrimPromise<TInstance>.s_completeFromAsyncResult, promise);
+
+            // If the IAsyncResult completed asynchronously, completing the promise will be handled by the callback.
+            // If it completed synchronously, we'll handle that here.
+            if (asyncResult.CompletedSynchronously)
+            {
+                Debug.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed.");
+                promise.Complete(thisRef, endMethod, asyncResult, requiresSynchronization: false);
+            }
+
+            // Return the promise
+            return promise;
+        }
+
+        /// <summary>
+        /// A specialized task used by FromAsyncTrim.  Stores relevant information as instance
+        /// state so that we can avoid unnecessary closure/delegate allocations.
+        /// </summary>
+        /// <typeparam name="TInstance">Specifies the type of the instance on which the APM implementation lives.</typeparam>
+        private sealed class FromAsyncTrimPromise<TInstance> : Task<TResult> where TInstance : class
+        {
+            /// <summary>A cached delegate used as the callback for the BeginXx method.</summary>
+            internal static readonly AsyncCallback s_completeFromAsyncResult = CompleteFromAsyncResult;
+
+            /// <summary>A reference to the object on which the begin/end methods are invoked.</summary>
+            private TInstance m_thisRef;
+            /// <summary>The end method.</summary>
+            private Func<TInstance, IAsyncResult, TResult> m_endMethod;
+
+            /// <summary>Initializes the promise.</summary>
+            /// <param name="thisRef">A reference to the object on which the begin/end methods are invoked.</param>
+            /// <param name="endMethod">The end method.</param>
+            internal FromAsyncTrimPromise(TInstance thisRef, Func<TInstance, IAsyncResult, TResult> endMethod) : base()
+            {
+                Debug.Assert(thisRef != null, "Expected a non-null thisRef");
+                Debug.Assert(endMethod != null, "Expected a non-null endMethod");
+                m_thisRef = thisRef;
+                m_endMethod = endMethod;
+            }
+
+            /// <summary>
+            /// Completes the asynchronous operation using information in the IAsyncResult.  
+            /// IAsyncResult.AsyncState needs to be the FromAsyncTrimPromise to complete.
+            /// </summary>
+            /// <param name="asyncResult">The IAsyncResult for the async operation.</param>
+            internal static void CompleteFromAsyncResult(IAsyncResult asyncResult)
+            {
+                // Validate argument
+                if (asyncResult == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.asyncResult);
+
+                var promise = asyncResult.AsyncState as FromAsyncTrimPromise<TInstance>;
+                if (promise == null) ThrowHelper.ThrowArgumentException(ExceptionResource.InvalidOperation_WrongAsyncResultOrEndCalledMultiple, ExceptionArgument.asyncResult);
+
+                // Grab the relevant state and then null it out so that the task doesn't hold onto the state unnecessarily
+                var thisRef = promise.m_thisRef;
+                var endMethod = promise.m_endMethod;
+                promise.m_thisRef = default;
+                promise.m_endMethod = null;
+                if (endMethod == null) ThrowHelper.ThrowArgumentException(ExceptionResource.InvalidOperation_WrongAsyncResultOrEndCalledMultiple, ExceptionArgument.asyncResult);
+
+                // Complete the promise.  If the IAsyncResult completed synchronously,
+                // we'll instead complete the promise at the call site.
+                if (!asyncResult.CompletedSynchronously)
+                {
+                    promise.Complete(thisRef, endMethod, asyncResult, requiresSynchronization: true);
+                }
+            }
+
+            /// <summary>Completes the promise.</summary>
+            /// <param name="requiresSynchronization">
+            /// true if synchronization is needed to completed the task;
+            /// false if the task may be completed without synchronization
+            /// because it hasn't been handed out.
+            /// </param>
+            /// <param name="thisRef">The target instance on which the end method should be called.</param>
+            /// <param name="endMethod">The end method to call to retrieve the result.</param>
+            /// <param name="asyncResult">The IAsyncResult for the async operation.</param>
+            /// <param name="requiresSynchronization">
+            /// Whether completing the task requires synchronization.  This should be true
+            /// unless absolutely sure that the task has not yet been handed out to any consumers.
+            /// </param>
+            internal void Complete(
+                TInstance thisRef, Func<TInstance, IAsyncResult, TResult> endMethod, IAsyncResult asyncResult,
+                bool requiresSynchronization)
+            {
+                Debug.Assert(!IsCompleted, "The task should not have been completed yet.");
+
+                // Run the end method and complete the task
+                bool successfullySet = false;
+                try
+                {
+                    var result = endMethod(thisRef, asyncResult);
+                    if (requiresSynchronization)
+                    {
+                        successfullySet = TrySetResult(result);
+                    }
+                    else
+                    {
+                        // If requiresSynchronization is false, we can use the DangerousSetResult
+                        // method, which uses no synchronization to complete the task.  This is
+                        // only valid when the operation is completing synchronously such
+                        // that the task has not yet been handed out to any consumers.
+                        DangerousSetResult(result);
+                        successfullySet = true;
+                    }
+                }
+                catch (OperationCanceledException oce)
+                {
+                    successfullySet = TrySetCanceled(oce.CancellationToken, oce);
+                }
+                catch (Exception exc)
+                {
+                    successfullySet = TrySetException(exc);
+                }
+                Debug.Assert(successfullySet, "Expected the task to not yet be completed");
+            }
+        }
+
+        // Utility method to create a canceled future-style task.
+        // Used by ContinueWhenAll/Any to bail out early on a pre-canceled token.
+        private static Task<TResult> CreateCanceledTask(TaskContinuationOptions continuationOptions, CancellationToken ct)
+        {
+            TaskCreationOptions tco;
+            InternalTaskOptions dontcare;
+            Task.CreationOptionsFromContinuationOptions(continuationOptions, out tco, out dontcare);
+            return new Task<TResult>(true, default, tco, ct);
+        }
+
+        //
+        // ContinueWhenAll() methods
+        //
+
+        /// <summary>
+        /// Creates a continuation <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see> 
+        /// that will be started upon the completion of a set of provided Tasks.
+        /// </summary>
+        /// <param name="tasks">The array of tasks from which to continue.</param>
+        /// <param name="continuationFunction">The function delegate to execute when all tasks in 
+        /// the <paramref name="tasks"/> array have completed.</param>
+        /// <returns>The new continuation <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the 
+        /// <paramref name="tasks"/> array is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the 
+        /// <paramref name="continuationFunction"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the 
+        /// <paramref name="tasks"/> array contains a null value.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the 
+        /// <paramref name="tasks"/> array is empty.</exception>
+        public Task<TResult> ContinueWhenAll(Task[] tasks, Func<Task[], TResult> continuationFunction)
+        {
+            if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction);
+
+            return ContinueWhenAllImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler);
+        }
+
+        /// <summary>
+        /// Creates a continuation <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see> 
+        /// that will be started upon the completion of a set of provided Tasks.
+        /// </summary>
+        /// <param name="tasks">The array of tasks from which to continue.</param>
+        /// <param name="continuationFunction">The function delegate to execute when all tasks in 
+        /// the <paramref name="tasks"/> array have completed.</param>
+        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken">CancellationToken</see> 
+        /// that will be assigned to the new continuation task.</param>
+        /// <returns>The new continuation <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the 
+        /// <paramref name="tasks"/> array is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the 
+        /// <paramref name="continuationFunction"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the 
+        /// <paramref name="tasks"/> array contains a null value.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the 
+        /// <paramref name="tasks"/> array is empty.</exception>
+        /// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
+        /// has already been disposed.
+        /// </exception>
+        public Task<TResult> ContinueWhenAll(Task[] tasks, Func<Task[], TResult> continuationFunction, CancellationToken cancellationToken)
+        {
+            if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction);
+
+            return ContinueWhenAllImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler);
+        }
+
+        /// <summary>
+        /// Creates a continuation <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>
+        /// that will be started upon the completion of a set of provided Tasks.
+        /// </summary>
+        /// <param name="tasks">The array of tasks from which to continue.</param>
+        /// <param name="continuationFunction">The function delegate to execute when all tasks in the <paramref
+        /// name="tasks"/> array have completed.</param>
+        /// <param name="continuationOptions">The <see cref="System.Threading.Tasks.TaskContinuationOptions">
+        /// TaskContinuationOptions</see> value that controls the behavior of
+        /// the created continuation <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>.</param>
+        /// <returns>The new continuation <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="continuationFunction"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array contains a null value.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is empty.</exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">The exception that is thrown when the
+        /// <paramref name="continuationOptions"/> argument specifies an invalid TaskContinuationOptions
+        /// value.</exception>
+        /// <remarks>
+        /// The NotOn* and OnlyOn* <see cref="System.Threading.Tasks.TaskContinuationOptions">TaskContinuationOptions</see>, 
+        /// which constrain for which <see cref="System.Threading.Tasks.TaskStatus">TaskStatus</see> states a continuation 
+        /// will be executed, are illegal with ContinueWhenAll.
+        /// </remarks>
+        public Task<TResult> ContinueWhenAll(Task[] tasks, Func<Task[], TResult> continuationFunction, TaskContinuationOptions continuationOptions)
+        {
+            if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction);
+
+            return ContinueWhenAllImpl(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler);
+        }
+
+        /// <summary>
+        /// Creates a continuation <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>
+        /// that will be started upon the completion of a set of provided Tasks.
+        /// </summary>
+        /// <param name="tasks">The array of tasks from which to continue.</param>
+        /// <param name="continuationFunction">The function delegate to execute when all tasks in the <paramref
+        /// name="tasks"/> array have completed.</param>
+        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken">CancellationToken</see> 
+        /// that will be assigned to the new continuation task.</param>
+        /// <param name="continuationOptions">The <see cref="System.Threading.Tasks.TaskContinuationOptions">
+        /// TaskContinuationOptions</see> value that controls the behavior of
+        /// the created continuation <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>.</param>
+        /// <param name="scheduler">The <see cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see>
+        /// that is used to schedule the created continuation <see
+        /// cref="T:System.Threading.Tasks.Task">Task</see>.</param>
+        /// <returns>The new continuation <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="continuationFunction"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="scheduler"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array contains a null value.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is empty.</exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">The exception that is thrown when the
+        /// <paramref name="continuationOptions"/> argument specifies an invalid TaskContinuationOptions
+        /// value.</exception>
+        /// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
+        /// has already been disposed.
+        /// </exception>
+        /// <remarks>
+        /// The NotOn* and OnlyOn* <see cref="System.Threading.Tasks.TaskContinuationOptions">TaskContinuationOptions</see>, 
+        /// which constrain for which <see cref="System.Threading.Tasks.TaskStatus">TaskStatus</see> states a continuation 
+        /// will be executed, are illegal with ContinueWhenAll.
+        /// </remarks>
+        public Task<TResult> ContinueWhenAll(Task[] tasks, Func<Task[], TResult> continuationFunction,
+            CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
+        {
+            if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction);
+
+            return ContinueWhenAllImpl(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler);
+        }
+
+        /// <summary>
+        /// Creates a continuation <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>
+        /// that will be started upon the completion of a set of provided Tasks.
+        /// </summary>
+        /// <typeparam name="TAntecedentResult">The type of the result of the antecedent <paramref name="tasks"/>.</typeparam>
+        /// <param name="tasks">The array of tasks from which to continue.</param>
+        /// <param name="continuationFunction">The function delegate to execute when all tasks in the
+        /// <paramref name="tasks"/> array have completed.</param>
+        /// <returns>The new continuation <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="continuationFunction"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array contains a null value.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is empty.</exception>
+        public Task<TResult> ContinueWhenAll<TAntecedentResult>(Task<TAntecedentResult>[] tasks, Func<Task<TAntecedentResult>[], TResult> continuationFunction)
+        {
+            if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction);
+
+            return ContinueWhenAllImpl<TAntecedentResult>(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler);
+        }
+
+        /// <summary>
+        /// Creates a continuation <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>
+        /// that will be started upon the completion of a set of provided Tasks.
+        /// </summary>
+        /// <typeparam name="TAntecedentResult">The type of the result of the antecedent <paramref name="tasks"/>.</typeparam>
+        /// <param name="tasks">The array of tasks from which to continue.</param>
+        /// <param name="continuationFunction">The function delegate to execute when all tasks in the
+        /// <paramref name="tasks"/> array have completed.</param>
+        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken">CancellationToken</see> 
+        /// that will be assigned to the new continuation task.</param>
+        /// <returns>The new continuation <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="continuationFunction"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array contains a null value.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is empty.</exception>
+        /// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
+        /// has already been disposed.
+        /// </exception>
+        public Task<TResult> ContinueWhenAll<TAntecedentResult>(Task<TAntecedentResult>[] tasks, Func<Task<TAntecedentResult>[], TResult> continuationFunction,
+            CancellationToken cancellationToken)
+        {
+            if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction);
+
+            return ContinueWhenAllImpl<TAntecedentResult>(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler);
+        }
+
+        /// <summary>
+        /// Creates a continuation <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>
+        /// that will be started upon the completion of a set of provided Tasks.
+        /// </summary>
+        /// <typeparam name="TAntecedentResult">The type of the result of the antecedent <paramref name="tasks"/>.</typeparam>
+        /// <param name="tasks">The array of tasks from which to continue.</param>
+        /// <param name="continuationFunction">The function delegate to execute when all tasks in the
+        /// <paramref name="tasks"/> array have completed.</param>
+        /// <param name="continuationOptions">The <see cref="System.Threading.Tasks.TaskContinuationOptions">
+        /// TaskContinuationOptions</see> value that controls the behavior of
+        /// the created continuation <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>.</param>
+        /// <returns>The new continuation <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="continuationFunction"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array contains a null value.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is empty.</exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">The exception that is thrown when the
+        /// <paramref name="continuationOptions"/> argument specifies an invalid TaskContinuationOptions
+        /// value.</exception>
+        /// <remarks>
+        /// The NotOn* and OnlyOn* <see cref="System.Threading.Tasks.TaskContinuationOptions">TaskContinuationOptions</see>, 
+        /// which constrain for which <see cref="System.Threading.Tasks.TaskStatus">TaskStatus</see> states a continuation 
+        /// will be executed, are illegal with ContinueWhenAll.
+        /// </remarks>
+        public Task<TResult> ContinueWhenAll<TAntecedentResult>(Task<TAntecedentResult>[] tasks, Func<Task<TAntecedentResult>[], TResult> continuationFunction,
+            TaskContinuationOptions continuationOptions)
+        {
+            if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction);
+
+            return ContinueWhenAllImpl<TAntecedentResult>(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler);
+        }
+
+        /// <summary>
+        /// Creates a continuation <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>
+        /// that will be started upon the completion of a set of provided Tasks.
+        /// </summary>
+        /// <typeparam name="TAntecedentResult">The type of the result of the antecedent <paramref name="tasks"/>.</typeparam>
+        /// <param name="tasks">The array of tasks from which to continue.</param>
+        /// <param name="continuationFunction">The function delegate to execute when all tasks in the
+        /// <paramref name="tasks"/> array have completed.</param>
+        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken">CancellationToken</see> 
+        /// that will be assigned to the new continuation task.</param>
+        /// <param name="continuationOptions">The <see cref="System.Threading.Tasks.TaskContinuationOptions">
+        /// TaskContinuationOptions</see> value that controls the behavior of
+        /// the created continuation <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>.</param>
+        /// <param name="scheduler">The <see cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see>
+        /// that is used to schedule the created continuation <see
+        /// cref="T:System.Threading.Tasks.Task{TResult}"/>.</param>
+        /// <returns>The new continuation <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="continuationFunction"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="scheduler"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array contains a null value.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is empty.</exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">The exception that is thrown when the
+        /// <paramref name="continuationOptions"/> argument specifies an invalid TaskContinuationOptions
+        /// value.</exception>
+        /// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
+        /// has already been disposed.
+        /// </exception>
+        /// <remarks>
+        /// The NotOn* and OnlyOn* <see cref="System.Threading.Tasks.TaskContinuationOptions">TaskContinuationOptions</see>, 
+        /// which constrain for which <see cref="System.Threading.Tasks.TaskStatus">TaskStatus</see> states a continuation 
+        /// will be executed, are illegal with ContinueWhenAll.
+        /// </remarks>
+        public Task<TResult> ContinueWhenAll<TAntecedentResult>(Task<TAntecedentResult>[] tasks, Func<Task<TAntecedentResult>[], TResult> continuationFunction,
+            CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
+        {
+            if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction);
+
+            return ContinueWhenAllImpl<TAntecedentResult>(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler);
+        }
+
+
+        // Core implementation of ContinueWhenAll -- the generic version
+        // Note: if you make any changes to this method, please do the same to the non-generic version too. 
+        internal static Task<TResult> ContinueWhenAllImpl<TAntecedentResult>(Task<TAntecedentResult>[] tasks,
+            Func<Task<TAntecedentResult>[], TResult> continuationFunction, Action<Task<TAntecedentResult>[]> continuationAction,
+            TaskContinuationOptions continuationOptions, CancellationToken cancellationToken, TaskScheduler scheduler)
+        {
+            // check arguments
+            TaskFactory.CheckMultiTaskContinuationOptions(continuationOptions);
+            if (tasks == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.tasks);
+            //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 tasks array and make defensive copy
+            Task<TAntecedentResult>[] tasksCopy = TaskFactory.CheckMultiContinuationTasksAndCopy<TAntecedentResult>(tasks);
+
+            // Bail early if cancellation has been requested.
+            if (cancellationToken.IsCancellationRequested
+                && ((continuationOptions & TaskContinuationOptions.LazyCancellation) == 0)
+                )
+            {
+                return CreateCanceledTask(continuationOptions, cancellationToken);
+            }
+
+            // Call common ContinueWhenAll() setup logic, extract starter task.
+            var starter = TaskFactory.CommonCWAllLogic(tasksCopy);
+
+            // returned continuation task, off of starter
+            if (continuationFunction != null)
+            {
+                return starter.ContinueWith<TResult>(
+                   // use a cached delegate
+                   GenericDelegateCache<TAntecedentResult, TResult>.CWAllFuncDelegate,
+                   continuationFunction, scheduler, cancellationToken, continuationOptions);
+            }
+            else
+            {
+                Debug.Assert(continuationAction != null);
+
+                return starter.ContinueWith<TResult>(
+                   // use a cached delegate
+                   GenericDelegateCache<TAntecedentResult, TResult>.CWAllActionDelegate,
+                   continuationAction, scheduler, cancellationToken, continuationOptions);
+            }
+        }
+
+        // Core implementation of ContinueWhenAll -- the non-generic version
+        // Note: if you make any changes to this method, please do the same to the generic version too. 
+        internal static Task<TResult> ContinueWhenAllImpl(Task[] tasks,
+            Func<Task[], TResult> continuationFunction, Action<Task[]> continuationAction,
+            TaskContinuationOptions continuationOptions, CancellationToken cancellationToken, TaskScheduler scheduler)
+        {
+            // check arguments
+            TaskFactory.CheckMultiTaskContinuationOptions(continuationOptions);
+            if (tasks == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.tasks);
+            //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 tasks array and make defensive copy
+            Task[] tasksCopy = TaskFactory.CheckMultiContinuationTasksAndCopy(tasks);
+
+            // Bail early if cancellation has been requested.
+            if (cancellationToken.IsCancellationRequested
+                && ((continuationOptions & TaskContinuationOptions.LazyCancellation) == 0)
+                )
+            {
+                return CreateCanceledTask(continuationOptions, cancellationToken);
+            }
+
+            // Perform common ContinueWhenAll() setup logic, extract starter task
+            var starter = TaskFactory.CommonCWAllLogic(tasksCopy);
+
+            // returned continuation task, off of starter
+            if (continuationFunction != null)
+            {
+                return starter.ContinueWith(
+                    //the following delegate avoids closure capture as much as possible
+                    //completedTasks.Result == tasksCopy;
+                    //state == continuationFunction
+                    (completedTasks, state) =>
+                    {
+                        completedTasks.NotifyDebuggerOfWaitCompletionIfNecessary();
+                        return ((Func<Task[], TResult>)state)(completedTasks.Result);
+                    },
+                    continuationFunction, scheduler, cancellationToken, continuationOptions);
+            }
+            else
+            {
+                Debug.Assert(continuationAction != null);
+                return starter.ContinueWith<TResult>(
+                   //the following delegate avoids closure capture as much as possible
+                   //completedTasks.Result == tasksCopy;
+                   //state == continuationAction
+                   (completedTasks, state) =>
+                   {
+                       completedTasks.NotifyDebuggerOfWaitCompletionIfNecessary();
+                       ((Action<Task[]>)state)(completedTasks.Result); return default;
+                   },
+                   continuationAction, scheduler, cancellationToken, continuationOptions);
+            }
+        }
+
+        //
+        // ContinueWhenAny() methods
+        //
+
+        /// <summary>
+        /// Creates a continuation <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>
+        /// that will be started upon the completion of any Task in the provided set.
+        /// </summary>
+        /// <param name="tasks">The array of tasks from which to continue when one task completes.</param>
+        /// <param name="continuationFunction">The function delegate to execute when one task in the <paramref
+        /// name="tasks"/> array completes.</param>
+        /// <returns>The new continuation <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="continuationFunction"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array contains a null value.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is empty.</exception>
+        public Task<TResult> ContinueWhenAny(Task[] tasks, Func<Task, TResult> continuationFunction)
+        {
+            if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction);
+
+            return ContinueWhenAnyImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler);
+        }
+
+        /// <summary>
+        /// Creates a continuation <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>
+        /// that will be started upon the completion of any Task in the provided set.
+        /// </summary>
+        /// <param name="tasks">The array of tasks from which to continue when one task completes.</param>
+        /// <param name="continuationFunction">The function delegate to execute when one task in the <paramref
+        /// name="tasks"/> array completes.</param>
+        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken">CancellationToken</see> 
+        /// that will be assigned to the new continuation task.</param>
+        /// <returns>The new continuation <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="continuationFunction"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array contains a null value.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is empty.</exception>
+        /// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
+        /// has already been disposed.
+        /// </exception>
+        public Task<TResult> ContinueWhenAny(Task[] tasks, Func<Task, TResult> continuationFunction, CancellationToken cancellationToken)
+        {
+            if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction);
+
+            return ContinueWhenAnyImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler);
+        }
+
+        /// <summary>
+        /// Creates a continuation <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>
+        /// that will be started upon the completion of any Task in the provided set.
+        /// </summary>
+        /// <param name="tasks">The array of tasks from which to continue when one task completes.</param>
+        /// <param name="continuationFunction">The function delegate to execute when one task in the <paramref
+        /// name="tasks"/> array completes.</param>
+        /// <param name="continuationOptions">The <see cref="System.Threading.Tasks.TaskContinuationOptions">
+        /// TaskContinuationOptions</see> value that controls the behavior of
+        /// the created continuation <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>.</param>
+        /// <returns>The new continuation <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="continuationFunction"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array contains a null value.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is empty.</exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">The exception that is thrown when the
+        /// <paramref name="continuationOptions"/> argument specifies an invalid TaskContinuationOptions
+        /// value.</exception>
+        /// <remarks>
+        /// The NotOn* and OnlyOn* <see cref="System.Threading.Tasks.TaskContinuationOptions">TaskContinuationOptions</see>, 
+        /// which constrain for which <see cref="System.Threading.Tasks.TaskStatus">TaskStatus</see> states a continuation 
+        /// will be executed, are illegal with ContinueWhenAny.
+        /// </remarks>
+        public Task<TResult> ContinueWhenAny(Task[] tasks, Func<Task, TResult> continuationFunction, TaskContinuationOptions continuationOptions)
+        {
+            if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction);
+
+            return ContinueWhenAnyImpl(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler);
+        }
+
+        /// <summary>
+        /// Creates a continuation <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>
+        /// that will be started upon the completion of any Task in the provided set.
+        /// </summary>
+        /// <param name="tasks">The array of tasks from which to continue when one task completes.</param>
+        /// <param name="continuationFunction">The function delegate to execute when one task in the <paramref
+        /// name="tasks"/> array completes.</param>
+        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken">CancellationToken</see> 
+        /// that will be assigned to the new continuation task.</param>
+        /// <param name="continuationOptions">The <see cref="System.Threading.Tasks.TaskContinuationOptions">
+        /// TaskContinuationOptions</see> value that controls the behavior of
+        /// the created continuation <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>.</param>
+        /// <param name="scheduler">The <see cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see>
+        /// that is used to schedule the created continuation <see
+        /// cref="T:System.Threading.Tasks.Task">Task</see>.</param>
+        /// <returns>The new continuation <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="continuationFunction"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="scheduler"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array contains a null value.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is empty.</exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">The exception that is thrown when the
+        /// <paramref name="continuationOptions"/> argument specifies an invalid TaskContinuationOptions
+        /// value.</exception>
+        /// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
+        /// has already been disposed.
+        /// </exception>
+        /// <remarks>
+        /// The NotOn* and OnlyOn* <see cref="System.Threading.Tasks.TaskContinuationOptions">TaskContinuationOptions</see>, 
+        /// which constrain for which <see cref="System.Threading.Tasks.TaskStatus">TaskStatus</see> states a continuation 
+        /// will be executed, are illegal with ContinueWhenAny.
+        /// </remarks>
+        public Task<TResult> ContinueWhenAny(Task[] tasks, Func<Task, TResult> continuationFunction,
+            CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
+        {
+            if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction);
+
+            return ContinueWhenAnyImpl(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler);
+        }
+
+        /// <summary>
+        /// Creates a continuation <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>
+        /// that will be started upon the completion of any Task in the provided set.
+        /// </summary>
+        /// <typeparam name="TAntecedentResult">The type of the result of the antecedent <paramref name="tasks"/>.</typeparam>
+        /// <param name="tasks">The array of tasks from which to continue when one task completes.</param>
+        /// <param name="continuationFunction">The function delegate to execute when one task in the
+        /// <paramref name="tasks"/> array completes.</param>
+        /// <returns>The new continuation <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="continuationFunction"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array contains a null value.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is empty.</exception>
+        public Task<TResult> ContinueWhenAny<TAntecedentResult>(Task<TAntecedentResult>[] tasks, Func<Task<TAntecedentResult>, TResult> continuationFunction)
+        {
+            if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction);
+
+            return ContinueWhenAnyImpl<TAntecedentResult>(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler);
+        }
+
+        /// <summary>
+        /// Creates a continuation <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>
+        /// that will be started upon the completion of any Task in the provided set.
+        /// </summary>
+        /// <typeparam name="TAntecedentResult">The type of the result of the antecedent <paramref name="tasks"/>.</typeparam>
+        /// <param name="tasks">The array of tasks from which to continue when one task completes.</param>
+        /// <param name="continuationFunction">The function delegate to execute when one task in the
+        /// <paramref name="tasks"/> array completes.</param>
+        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken">CancellationToken</see> 
+        /// that will be assigned to the new continuation task.</param>
+        /// <returns>The new continuation <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="continuationFunction"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array contains a null value.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is empty.</exception>
+        /// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
+        /// has already been disposed.
+        /// </exception>
+        public Task<TResult> ContinueWhenAny<TAntecedentResult>(Task<TAntecedentResult>[] tasks, Func<Task<TAntecedentResult>, TResult> continuationFunction,
+            CancellationToken cancellationToken)
+        {
+            if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction);
+
+            return ContinueWhenAnyImpl<TAntecedentResult>(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler);
+        }
+
+        /// <summary>
+        /// Creates a continuation <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>
+        /// that will be started upon the completion of any Task in the provided set.
+        /// </summary>
+        /// <typeparam name="TAntecedentResult">The type of the result of the antecedent <paramref name="tasks"/>.</typeparam>
+        /// <param name="tasks">The array of tasks from which to continue when one task completes.</param>
+        /// <param name="continuationFunction">The function delegate to execute when one task in the
+        /// <paramref name="tasks"/> array completes.</param>
+        /// <param name="continuationOptions">The <see cref="System.Threading.Tasks.TaskContinuationOptions">
+        /// TaskContinuationOptions</see> value that controls the behavior of
+        /// the created continuation <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>.</param>
+        /// <returns>The new continuation <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="continuationFunction"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array contains a null value.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is empty.</exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">The exception that is thrown when the
+        /// <paramref name="continuationOptions"/> argument specifies an invalid TaskContinuationOptions
+        /// value.</exception>
+        /// <remarks>
+        /// The NotOn* and OnlyOn* <see cref="System.Threading.Tasks.TaskContinuationOptions">TaskContinuationOptions</see>, 
+        /// which constrain for which <see cref="System.Threading.Tasks.TaskStatus">TaskStatus</see> states a continuation 
+        /// will be executed, are illegal with ContinueWhenAny.
+        /// </remarks>
+        public Task<TResult> ContinueWhenAny<TAntecedentResult>(Task<TAntecedentResult>[] tasks, Func<Task<TAntecedentResult>, TResult> continuationFunction,
+            TaskContinuationOptions continuationOptions)
+        {
+            if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction);
+
+            return ContinueWhenAnyImpl<TAntecedentResult>(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler);
+        }
+
+        /// <summary>
+        /// Creates a continuation <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>
+        /// that will be started upon the completion of any Task in the provided set.
+        /// </summary>
+        /// <typeparam name="TAntecedentResult">The type of the result of the antecedent <paramref name="tasks"/>.</typeparam>
+        /// <param name="tasks">The array of tasks from which to continue when one task completes.</param>
+        /// <param name="continuationFunction">The function delegate to execute when one task in the
+        /// <paramref name="tasks"/> array completes.</param>
+        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken">CancellationToken</see> 
+        /// that will be assigned to the new continuation task.</param>
+        /// <param name="continuationOptions">The <see cref="System.Threading.Tasks.TaskContinuationOptions">
+        /// TaskContinuationOptions</see> value that controls the behavior of
+        /// the created continuation <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>.</param>
+        /// <param name="scheduler">The <see cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see>
+        /// that is used to schedule the created continuation <see
+        /// cref="T:System.Threading.Tasks.Task{TResult}"/>.</param>
+        /// <returns>The new continuation <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="continuationFunction"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="scheduler"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array contains a null value.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is empty.</exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">The exception that is thrown when the
+        /// <paramref name="continuationOptions"/> argument specifies an invalid TaskContinuationOptions
+        /// value.</exception>
+        /// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
+        /// has already been disposed.
+        /// </exception>
+        /// <remarks>
+        /// The NotOn* and OnlyOn* <see cref="System.Threading.Tasks.TaskContinuationOptions">TaskContinuationOptions</see>, 
+        /// which constrain for which <see cref="System.Threading.Tasks.TaskStatus">TaskStatus</see> states a continuation 
+        /// will be executed, are illegal with ContinueWhenAny.
+        /// </remarks>
+        public Task<TResult> ContinueWhenAny<TAntecedentResult>(Task<TAntecedentResult>[] tasks, Func<Task<TAntecedentResult>, TResult> continuationFunction,
+            CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
+        {
+            if (continuationFunction == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction);
+
+            return ContinueWhenAnyImpl<TAntecedentResult>(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler);
+        }
+
+        // Core implementation of ContinueWhenAny, non-generic version
+        // Note: if you make any changes to this method, be sure to do the same to the generic version 
+        internal static Task<TResult> ContinueWhenAnyImpl(Task[] tasks,
+            Func<Task, TResult> continuationFunction, Action<Task> continuationAction,
+            TaskContinuationOptions continuationOptions, CancellationToken cancellationToken, TaskScheduler scheduler)
+        {
+            // check arguments
+            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
+            Debug.Assert((continuationFunction != null) != (continuationAction != null), "Expected exactly one of endFunction/endAction to be non-null");
+            if (scheduler == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler);
+
+            // Call common ContinueWhenAny() setup logic, extract starter
+            Task<Task> starter = TaskFactory.CommonCWAnyLogic(tasks);
+
+            // Bail early if cancellation has been requested.
+            if (cancellationToken.IsCancellationRequested
+                && ((continuationOptions & TaskContinuationOptions.LazyCancellation) == 0)
+                )
+            {
+                return CreateCanceledTask(continuationOptions, cancellationToken);
+            }
+
+            // returned continuation task, off of starter
+            if (continuationFunction != null)
+            {
+                return starter.ContinueWith(
+                     //the following delegate avoids closure capture as much as possible
+                     //completedTask.Result is the winning task; state == continuationAction
+                     (completedTask, state) => { return ((Func<Task, TResult>)state)(completedTask.Result); },
+                     continuationFunction, scheduler, cancellationToken, continuationOptions);
+            }
+            else
+            {
+                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
+                    (completedTask, state) => { ((Action<Task>)state)(completedTask.Result); return default; },
+                    continuationAction, scheduler, cancellationToken, continuationOptions);
+            }
+        }
+
+
+        // Core implementation of ContinueWhenAny, generic version
+        // Note: if you make any changes to this method, be sure to do the same to the non-generic version 
+        internal static Task<TResult> ContinueWhenAnyImpl<TAntecedentResult>(Task<TAntecedentResult>[] tasks,
+            Func<Task<TAntecedentResult>, TResult> continuationFunction, Action<Task<TAntecedentResult>> continuationAction,
+            TaskContinuationOptions continuationOptions, CancellationToken cancellationToken, TaskScheduler scheduler)
+        {
+            // check arguments
+            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
+            Debug.Assert((continuationFunction != null) != (continuationAction != null), "Expected exactly one of endFunction/endAction to be non-null");
+            if (scheduler == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler);
+
+            // Call common ContinueWhenAny setup logic, extract starter
+            var starter = TaskFactory.CommonCWAnyLogic(tasks);
+
+            // Bail early if cancellation has been requested.
+            if (cancellationToken.IsCancellationRequested
+                && ((continuationOptions & TaskContinuationOptions.LazyCancellation) == 0)
+                )
+            {
+                return CreateCanceledTask(continuationOptions, cancellationToken);
+            }
+
+            // returned continuation task, off of starter
+            if (continuationFunction != null)
+            {
+                return starter.ContinueWith<TResult>(
+                    // Use a cached delegate
+                    GenericDelegateCache<TAntecedentResult, TResult>.CWAnyFuncDelegate,
+                    continuationFunction, scheduler, cancellationToken, continuationOptions);
+            }
+            else
+            {
+                Debug.Assert(continuationAction != null);
+                return starter.ContinueWith<TResult>(
+                    // Use a cached delegate
+                    GenericDelegateCache<TAntecedentResult, TResult>.CWAnyActionDelegate,
+                    continuationAction, scheduler, cancellationToken, continuationOptions);
+            }
+        }
+    }
+
+    // For the ContinueWhenAnyImpl/ContinueWhenAllImpl methods that are generic on TAntecedentResult,
+    // the compiler won't cache the internal ContinueWith delegate because it is generic on both
+    // TAntecedentResult and TResult.  The GenericDelegateCache serves as a cache for those delegates.
+    internal static class GenericDelegateCache<TAntecedentResult, TResult>
+    {
+        // ContinueWith delegate for TaskFactory<TResult>.ContinueWhenAnyImpl<TAntecedentResult>(non-null continuationFunction)
+        internal static Func<Task<Task>, object, TResult> CWAnyFuncDelegate =
+            (Task<Task> wrappedWinner, object state) =>
+            {
+                var func = (Func<Task<TAntecedentResult>, TResult>)state;
+                var arg = (Task<TAntecedentResult>)wrappedWinner.Result;
+                return func(arg);
+            };
+
+        // ContinueWith delegate for TaskFactory<TResult>.ContinueWhenAnyImpl<TAntecedentResult>(non-null continuationAction)
+        internal static Func<Task<Task>, object, TResult> CWAnyActionDelegate =
+            (Task<Task> wrappedWinner, object state) =>
+            {
+                var action = (Action<Task<TAntecedentResult>>)state;
+                var arg = (Task<TAntecedentResult>)wrappedWinner.Result;
+                action(arg);
+                return default;
+            };
+
+        // ContinueWith delegate for TaskFactory<TResult>.ContinueWhenAllImpl<TAntecedentResult>(non-null continuationFunction)
+        internal static Func<Task<Task<TAntecedentResult>[]>, object, TResult> CWAllFuncDelegate =
+            (Task<Task<TAntecedentResult>[]> wrappedAntecedents, object state) =>
+            {
+                wrappedAntecedents.NotifyDebuggerOfWaitCompletionIfNecessary();
+                var func = (Func<Task<TAntecedentResult>[], TResult>)state;
+                return func(wrappedAntecedents.Result);
+            };
+
+        // ContinueWith delegate for TaskFactory<TResult>.ContinueWhenAllImpl<TAntecedentResult>(non-null continuationAction)
+        internal static Func<Task<Task<TAntecedentResult>[]>, object, TResult> CWAllActionDelegate =
+            (Task<Task<TAntecedentResult>[]> wrappedAntecedents, object state) =>
+            {
+                wrappedAntecedents.NotifyDebuggerOfWaitCompletionIfNecessary();
+                var action = (Action<Task<TAntecedentResult>[]>)state;
+                action(wrappedAntecedents.Result);
+                return default;
+            };
+    }
+}

+ 29 - 0
mcs/class/System.Private.CoreLib/temp/GC.cs

@@ -0,0 +1,29 @@
+namespace System.Runtime
+{
+    public enum GCLargeObjectHeapCompactionMode
+    {
+        CompactOnce = 2,
+        Default = 1,
+    }
+    public enum GCLatencyMode
+    {
+        Batch = 0,
+        Interactive = 1,
+        LowLatency = 2,
+        NoGCRegion = 4,
+        SustainedLowLatency = 3,
+    }
+    public static partial class GCSettings
+    {
+        public static bool IsServerGC { get { throw null; } }
+        public static System.Runtime.GCLargeObjectHeapCompactionMode LargeObjectHeapCompactionMode { get { throw null; } set { } }
+        public static System.Runtime.GCLatencyMode LatencyMode { get { throw null; } set { } }        
+    }
+    
+    public sealed partial class MemoryFailPoint : System.Runtime.ConstrainedExecution.CriticalFinalizerObject, System.IDisposable
+    {
+        public MemoryFailPoint(int sizeInMegabytes) { }
+        public void Dispose() { }
+        ~MemoryFailPoint() { }
+    }
+}

+ 219 - 0
mcs/class/System.Private.CoreLib/temp/GCHandleCookieTable.cs

@@ -0,0 +1,219 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+#if MDA_SUPPORTED
+
+namespace System.Runtime.InteropServices
+{
+    using System;
+    using System.Collections.Generic;
+    using System.Threading;
+
+    using ObjectHandle = IntPtr;
+    using GCHandleCookie = IntPtr;
+
+    // Internal class used to map a GCHandle to an IntPtr. Instead of handing out the underlying CLR
+    // handle, we now hand out a cookie that can later be converted back to the CLR handle it 
+    // is associated with.
+
+    // NOTE:
+    // this implementation uses a single lock between FindOrAddHandle and RemoveHandleIfPresent which
+    // could create some scalability issues when this MDA is turned on.  if this is affecting perf
+    // then additional tuning work will be required.
+
+    internal class GCHandleCookieTable
+    {
+        private const int InitialHandleCount = 10;
+        private const int MaxListSize = 0xFFFFFF;
+        private const uint CookieMaskIndex = 0x00FFFFFF;
+        private const uint CookieMaskSentinal = 0xFF000000;
+
+        internal GCHandleCookieTable()
+        {
+            m_HandleList = new ObjectHandle[InitialHandleCount];
+            m_CycleCounts = new byte[InitialHandleCount];
+            m_HandleToCookieMap = new Dictionary<ObjectHandle, GCHandleCookie>(InitialHandleCount);
+            m_syncObject = new object();
+
+            for (int i = 0; i < InitialHandleCount; i++)
+            {
+                m_HandleList[i] = ObjectHandle.Zero;
+                m_CycleCounts[i] = 0;
+            }
+        }
+
+        // Retrieve a cookie for the passed in handle. If no cookie has yet been allocated for 
+        // this handle, one will be created. This method is thread safe.
+        internal GCHandleCookie FindOrAddHandle(ObjectHandle handle)
+        {
+            // Don't accept a null object handle
+            if (handle == ObjectHandle.Zero)
+                return GCHandleCookie.Zero;
+
+            GCHandleCookie cookie = GCHandleCookie.Zero;
+
+            lock (m_syncObject)
+            {
+                // First see if we already have a cookie for this handle.
+                if (m_HandleToCookieMap.ContainsKey(handle))
+                    return m_HandleToCookieMap[handle];
+
+                if ((m_FreeIndex < m_HandleList.Length) && (Volatile.Read(ref m_HandleList[m_FreeIndex]) == ObjectHandle.Zero))
+                {
+                    Volatile.Write(ref m_HandleList[m_FreeIndex],  handle);
+                    cookie = GetCookieFromData((uint)m_FreeIndex, m_CycleCounts[m_FreeIndex]);
+
+                    // Set our next guess just one higher as this index is now in use.
+                    // it's ok if this sets m_FreeIndex > m_HandleList.Length as this condition is
+                    // checked at the beginning of the if statement.
+                    ++m_FreeIndex;
+                }
+                else
+                {
+                    for (m_FreeIndex = 0; m_FreeIndex < MaxListSize; ++m_FreeIndex)
+                    {
+                        if (m_HandleList[m_FreeIndex] == ObjectHandle.Zero)
+                        {
+                            Volatile.Write(ref m_HandleList[m_FreeIndex], handle);
+                            cookie = GetCookieFromData((uint)m_FreeIndex, m_CycleCounts[m_FreeIndex]);
+
+                            // this will be our next guess for a free index.
+                            // it's ok if this sets m_FreeIndex > m_HandleList.Length
+                            // since we check for this condition in the if statement.
+                            ++m_FreeIndex;
+                            break;
+                        }
+
+                        if (m_FreeIndex + 1 == m_HandleList.Length)
+                            GrowArrays();
+                    }
+                }
+
+                if (cookie == GCHandleCookie.Zero)
+                    throw new OutOfMemoryException(SR.OutOfMemory_GCHandleMDA);
+
+                // This handle hasn't been added to the map yet so add it.
+                m_HandleToCookieMap.Add(handle, cookie);
+            }
+
+            return cookie;
+        }
+
+        // Get a handle.
+        internal ObjectHandle GetHandle(GCHandleCookie cookie)
+        {
+            ObjectHandle oh = ObjectHandle.Zero;
+
+            if (!ValidateCookie(cookie))
+                return ObjectHandle.Zero;
+
+            oh = Volatile.Read(ref m_HandleList[GetIndexFromCookie(cookie)]);
+
+            return oh;
+        }
+
+        // Remove the handle from the cookie table if it is present. 
+        //
+        internal void RemoveHandleIfPresent(ObjectHandle handle)
+        {
+            if (handle == ObjectHandle.Zero)
+                return;
+
+            lock (m_syncObject)
+            {
+                if (m_HandleToCookieMap.ContainsKey(handle))
+                {
+                    GCHandleCookie cookie = m_HandleToCookieMap[handle];
+
+                    // Remove it from the array first
+                    if (!ValidateCookie(cookie))
+                        return;
+
+                    int index = GetIndexFromCookie(cookie);
+
+                    m_CycleCounts[index]++;
+                    Volatile.Write(ref m_HandleList[index], ObjectHandle.Zero);
+
+                    // Remove it from the hashtable last
+                    m_HandleToCookieMap.Remove(handle);
+
+                    // Update our guess
+                    m_FreeIndex = index;
+                }
+            }
+        }
+
+        private bool ValidateCookie(GCHandleCookie cookie)
+        {
+            int index;
+            byte xorData;
+
+            GetDataFromCookie(cookie, out index, out xorData);
+
+            // Validate the index
+            if (index >= MaxListSize)
+                return false;
+
+            if (index >= m_HandleList.Length)
+                return false;
+
+            if (Volatile.Read(ref m_HandleList[index]) == ObjectHandle.Zero)
+                return false;
+
+            // Validate the xorData byte (this contains the cycle count and appdomain id).
+            byte ADID = (byte)(AppDomain.CurrentDomain.Id % 0xFF);
+            byte goodData = (byte)(Volatile.Read(ref m_CycleCounts[index]) ^ ADID);
+            if (xorData != goodData)
+                return false;
+
+            return true;
+        }
+
+        // Double the size of our arrays - must be called with the lock taken.
+        private void GrowArrays()
+        {
+            int CurrLength = m_HandleList.Length;
+
+            ObjectHandle[] newHandleList = new ObjectHandle[CurrLength * 2];
+            byte[] newCycleCounts = new byte[CurrLength * 2];
+
+            Array.Copy(m_HandleList, newHandleList, CurrLength);
+            Array.Copy(m_CycleCounts, newCycleCounts, CurrLength);
+
+            m_HandleList = newHandleList;
+            m_CycleCounts = newCycleCounts;
+        }
+
+        // Generate a cookie based on the index, cyclecount, and current domain id.
+        private GCHandleCookie GetCookieFromData(uint index, byte cycleCount)
+        {
+            byte ADID = (byte)(AppDomain.CurrentDomain.Id % 0xFF);
+            return (GCHandleCookie)(((cycleCount ^ ADID) << 24) + index + 1);
+        }
+
+        // Break down the cookie into its parts
+        private void GetDataFromCookie(GCHandleCookie cookie, out int index, out byte xorData)
+        {
+            uint intCookie = (uint)cookie;
+            index = (int)(intCookie & CookieMaskIndex) - 1;
+            xorData = (byte)((intCookie & CookieMaskSentinal) >> 24);
+        }
+
+        // Just get the index from the cookie
+        private int GetIndexFromCookie(GCHandleCookie cookie)
+        {
+            uint intCookie = (uint)cookie;
+            return (int)(intCookie & CookieMaskIndex) - 1;
+        }
+
+        private Dictionary<ObjectHandle, GCHandleCookie> m_HandleToCookieMap;
+        private volatile ObjectHandle[] m_HandleList;
+        private volatile byte[] m_CycleCounts;
+        private int m_FreeIndex;
+        private readonly object m_syncObject;
+    }
+}
+
+#endif
+

+ 597 - 0
mcs/class/System.Private.CoreLib/temp/TPLETWProvider.cs

@@ -0,0 +1,597 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
+//
+//
+//
+// EventSource for TPL.
+//
+// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
+
+using System;
+using System.Collections.Generic;
+using System.Text;
+using System.Security;
+using System.Runtime.CompilerServices;
+using System.Diagnostics.Tracing;
+
+using Internal.Runtime.CompilerServices;
+
+namespace System.Threading.Tasks
+{
+    /// <summary>Provides an event source for tracing TPL information.</summary>
+    [EventSource(
+        Name = "System.Threading.Tasks.TplEventSource",
+        Guid = "2e5dba47-a3d2-4d16-8ee0-6671ffdcd7b5",
+        LocalizationResources = "FxResources.System.Private.CoreLib.SR")]
+    internal sealed class TplEtwProvider : EventSource
+    {
+        /// Used to determine if tasks should generate Activity IDs for themselves
+        internal bool TasksSetActivityIds;        // This keyword is set
+        internal bool Debug;
+        private bool DebugActivityId;
+
+        /// <summary>
+        /// Get callbacks when the ETW sends us commands`
+        /// </summary>
+        protected override void OnEventCommand(EventCommandEventArgs command)
+        {
+#if !MONO
+            // To get the AsyncCausality events, we need to inform the AsyncCausalityTracer
+            if (command.Command == EventCommand.Enable)
+                AsyncCausalityTracer.EnableToETW(true);
+            else if (command.Command == EventCommand.Disable)
+                AsyncCausalityTracer.EnableToETW(false);
+#endif
+            if (IsEnabled(EventLevel.Informational, Keywords.TasksFlowActivityIds)) {
+#if !MONO
+                ActivityTracker.Instance.Enable();
+#endif
+            }
+            else
+                TasksSetActivityIds = IsEnabled(EventLevel.Informational, Keywords.TasksSetActivityIds);
+
+            Debug = IsEnabled(EventLevel.Informational, Keywords.Debug);
+            DebugActivityId = IsEnabled(EventLevel.Informational, Keywords.DebugActivityId);
+        }
+
+        /// <summary>
+        /// Defines the singleton instance for the TPL ETW provider.
+        /// The TPL Event provider GUID is {2e5dba47-a3d2-4d16-8ee0-6671ffdcd7b5}.
+        /// </summary>
+        public static readonly TplEtwProvider Log = new TplEtwProvider();
+
+        /// <summary>Prevent external instantiation.  All logging should go through the Log instance.</summary>
+        private TplEtwProvider() : base(new Guid(0x2e5dba47, 0xa3d2, 0x4d16, 0x8e, 0xe0, 0x66, 0x71, 0xff, 0xdc, 0xd7, 0xb5), "System.Threading.Tasks.TplEventSource") { }
+
+        /// <summary>Configured behavior of a task wait operation.</summary>
+        public enum TaskWaitBehavior : int
+        {
+            /// <summary>A synchronous wait.</summary>
+            Synchronous = 1,
+            /// <summary>An asynchronous await.</summary>
+            Asynchronous = 2
+        }
+
+        /// <summary>ETW tasks that have start/stop events.</summary>
+        public class Tasks // this name is important for EventSource
+        {
+            /// <summary>A parallel loop.</summary>
+            public const EventTask Loop = (EventTask)1;
+            /// <summary>A parallel invoke.</summary>
+            public const EventTask Invoke = (EventTask)2;
+            /// <summary>Executing a Task.</summary>
+            public const EventTask TaskExecute = (EventTask)3;
+            /// <summary>Waiting on a Task.</summary>
+            public const EventTask TaskWait = (EventTask)4;
+            /// <summary>A fork/join task within a loop or invoke.</summary>
+            public const EventTask ForkJoin = (EventTask)5;
+            /// <summary>A task is scheduled to execute.</summary>
+            public const EventTask TaskScheduled = (EventTask)6;
+            /// <summary>An await task continuation is scheduled to execute.</summary>
+            public const EventTask AwaitTaskContinuationScheduled = (EventTask)7;
+
+            /// <summary>AsyncCausalityFunctionality.</summary>
+            public const EventTask TraceOperation = (EventTask)8;
+            public const EventTask TraceSynchronousWork = (EventTask)9;
+        }
+
+        public class Keywords // thisname is important for EventSource
+        {
+            /// <summary>
+            /// Only the most basic information about the workings of the task library
+            /// This sets activity IDS and logs when tasks are schedules (or waits begin)
+            /// But are otherwise silent
+            /// </summary>
+            public const EventKeywords TaskTransfer = (EventKeywords)1;
+            /// <summary>
+            /// TaskTranser events plus events when tasks start and stop 
+            /// </summary>
+            public const EventKeywords Tasks = (EventKeywords)2;
+            /// <summary>
+            /// Events associted with the higher level parallel APIs
+            /// </summary>
+            public const EventKeywords Parallel = (EventKeywords)4;
+            /// <summary>
+            /// These are relatively verbose events that effectively just redirect
+            /// the windows AsyncCausalityTracer to ETW
+            /// </summary>
+            public const EventKeywords AsyncCausalityOperation = (EventKeywords)8;
+            public const EventKeywords AsyncCausalityRelation = (EventKeywords)0x10;
+            public const EventKeywords AsyncCausalitySynchronousWork = (EventKeywords)0x20;
+
+            /// <summary>
+            /// Emit the stops as well as the schedule/start events
+            /// </summary>
+            public const EventKeywords TaskStops = (EventKeywords)0x40;
+
+            /// <summary>
+            /// TasksFlowActivityIds indicate that activity ID flow from one task
+            /// to any task created by it. 
+            /// </summary>
+            public const EventKeywords TasksFlowActivityIds = (EventKeywords)0x80;
+
+            /// <summary>
+            /// Events related to the happenings of async methods.
+            /// </summary>
+            public const EventKeywords AsyncMethod = (EventKeywords)0x100;
+
+            /// <summary>
+            /// TasksSetActivityIds will cause the task operations to set Activity Ids 
+            /// This option is incompatible with TasksFlowActivityIds flow is ignored
+            /// if that keyword is set.   This option is likely to be removed in the future
+            /// </summary>
+            public const EventKeywords TasksSetActivityIds = (EventKeywords)0x10000;
+
+            /// <summary>
+            /// Relatively Verbose logging meant for debugging the Task library itself. Will probably be removed in the future
+            /// </summary>
+            public const EventKeywords Debug = (EventKeywords)0x20000;
+            /// <summary>
+            /// Relatively Verbose logging meant for debugging the Task library itself.  Will probably be removed in the future
+            /// </summary>
+            public const EventKeywords DebugActivityId = (EventKeywords)0x40000;
+        }
+
+        /// <summary>Enabled for all keywords.</summary>
+        private const EventKeywords ALL_KEYWORDS = (EventKeywords)(-1);
+
+        //-----------------------------------------------------------------------------------
+        //        
+        // TPL Event IDs (must be unique)
+        //
+
+        /// <summary>The beginning of a parallel loop.</summary>
+        private const int PARALLELLOOPBEGIN_ID = 1;
+        /// <summary>The ending of a parallel loop.</summary>
+        private const int PARALLELLOOPEND_ID = 2;
+        /// <summary>The beginning of a parallel invoke.</summary>
+        private const int PARALLELINVOKEBEGIN_ID = 3;
+        /// <summary>The ending of a parallel invoke.</summary>
+        private const int PARALLELINVOKEEND_ID = 4;
+        /// <summary>A task entering a fork/join construct.</summary>
+        private const int PARALLELFORK_ID = 5;
+        /// <summary>A task leaving a fork/join construct.</summary>
+        private const int PARALLELJOIN_ID = 6;
+
+        /// <summary>A task is scheduled to a task scheduler.</summary>
+        private const int TASKSCHEDULED_ID = 7;
+        /// <summary>A task is about to execute.</summary>
+        private const int TASKSTARTED_ID = 8;
+        /// <summary>A task has finished executing.</summary>
+        private const int TASKCOMPLETED_ID = 9;
+        /// <summary>A wait on a task is beginning.</summary>
+        private const int TASKWAITBEGIN_ID = 10;
+        /// <summary>A wait on a task is ending.</summary>
+        private const int TASKWAITEND_ID = 11;
+        /// <summary>A continuation of a task is scheduled.</summary>
+        private const int AWAITTASKCONTINUATIONSCHEDULED_ID = 12;
+        /// <summary>A continuation of a taskWaitEnd is complete </summary>
+        private const int TASKWAITCONTINUATIONCOMPLETE_ID = 13;
+        /// <summary>A continuation of a taskWaitEnd is complete </summary>
+        private const int TASKWAITCONTINUATIONSTARTED_ID = 19;
+
+        private const int TRACEOPERATIONSTART_ID = 14;
+        private const int TRACEOPERATIONSTOP_ID = 15;
+        private const int TRACEOPERATIONRELATION_ID = 16;
+        private const int TRACESYNCHRONOUSWORKSTART_ID = 17;
+        private const int TRACESYNCHRONOUSWORKSTOP_ID = 18;
+
+
+        //-----------------------------------------------------------------------------------
+        //        
+        // Task Events
+        //
+
+        // These are all verbose events, so we need to call IsEnabled(EventLevel.Verbose, ALL_KEYWORDS) 
+        // call. However since the IsEnabled(l,k) call is more expensive than IsEnabled(), we only want 
+        // to incur this cost when instrumentation is enabled. So the Task codepaths that call these
+        // event functions still do the check for IsEnabled()
+
+        #region TaskScheduled
+        /// <summary>
+        /// Fired when a task is queued to a TaskScheduler.
+        /// </summary>
+        /// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param>
+        /// <param name="OriginatingTaskID">The task ID.</param>
+        /// <param name="TaskID">The task ID.</param>
+        /// <param name="CreatingTaskID">The task ID</param>
+        /// <param name="TaskCreationOptions">The options used to create the task.</param>
+        [Event(TASKSCHEDULED_ID, Task = Tasks.TaskScheduled, Version = 1, Opcode = EventOpcode.Send,
+         Level = EventLevel.Informational, Keywords = Keywords.TaskTransfer | Keywords.Tasks)]
+        public void TaskScheduled(
+            int OriginatingTaskSchedulerID, int OriginatingTaskID,  // PFX_COMMON_EVENT_HEADER
+            int TaskID, int CreatingTaskID, int TaskCreationOptions, int appDomain)
+        {
+            // IsEnabled() call is an inlined quick check that makes this very fast when provider is off 
+            if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.TaskTransfer | Keywords.Tasks))
+            {
+                unsafe
+                {
+                    EventData* eventPayload = stackalloc EventData[6];
+                    eventPayload[0].Size = sizeof(int);
+                    eventPayload[0].DataPointer = ((IntPtr)(&OriginatingTaskSchedulerID));
+                    eventPayload[0].Reserved = 0;
+                    eventPayload[1].Size = sizeof(int);
+                    eventPayload[1].DataPointer = ((IntPtr)(&OriginatingTaskID));
+                    eventPayload[1].Reserved = 0;
+                    eventPayload[2].Size = sizeof(int);
+                    eventPayload[2].DataPointer = ((IntPtr)(&TaskID));
+                    eventPayload[2].Reserved = 0;
+                    eventPayload[3].Size = sizeof(int);
+                    eventPayload[3].DataPointer = ((IntPtr)(&CreatingTaskID));
+                    eventPayload[3].Reserved = 0;
+                    eventPayload[4].Size = sizeof(int);
+                    eventPayload[4].DataPointer = ((IntPtr)(&TaskCreationOptions));
+                    eventPayload[4].Reserved = 0;
+                    eventPayload[5].Size = sizeof(int);
+                    eventPayload[5].DataPointer = ((IntPtr)(&appDomain));
+                    eventPayload[5].Reserved = 0;
+                    if (TasksSetActivityIds)
+                    {
+                        Guid childActivityId = CreateGuidForTaskID(TaskID);
+                        WriteEventWithRelatedActivityIdCore(TASKSCHEDULED_ID, &childActivityId, 6, eventPayload);
+                    }
+                    else
+                        WriteEventCore(TASKSCHEDULED_ID, 6, eventPayload);
+                }
+            }
+        }
+        #endregion
+
+        #region TaskStarted
+        /// <summary>
+        /// Fired just before a task actually starts executing.
+        /// </summary>
+        /// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param>
+        /// <param name="OriginatingTaskID">The task ID.</param>
+        /// <param name="TaskID">The task ID.</param>
+        [Event(TASKSTARTED_ID,
+         Level = EventLevel.Informational, Keywords = Keywords.Tasks)]
+        public void TaskStarted(
+            int OriginatingTaskSchedulerID, int OriginatingTaskID,  // PFX_COMMON_EVENT_HEADER
+            int TaskID)
+        {
+            if (IsEnabled(EventLevel.Informational, Keywords.Tasks))
+                WriteEvent(TASKSTARTED_ID, OriginatingTaskSchedulerID, OriginatingTaskID, TaskID);
+        }
+        #endregion
+
+        #region TaskCompleted
+        /// <summary>
+        /// Fired right after a task finished executing.
+        /// </summary>
+        /// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param>
+        /// <param name="OriginatingTaskID">The task ID.</param>
+        /// <param name="TaskID">The task ID.</param>
+        /// <param name="IsExceptional">Whether the task completed due to an error.</param>
+        [Event(TASKCOMPLETED_ID, Version = 1,
+         Level = EventLevel.Informational, Keywords = Keywords.TaskStops)]
+        public void TaskCompleted(
+            int OriginatingTaskSchedulerID, int OriginatingTaskID,  // PFX_COMMON_EVENT_HEADER
+            int TaskID, bool IsExceptional)
+        {
+            if (IsEnabled(EventLevel.Informational, Keywords.Tasks))
+            {
+                unsafe
+                {
+                    EventData* eventPayload = stackalloc EventData[4];
+                    int isExceptionalInt = IsExceptional ? 1 : 0;
+                    eventPayload[0].Size = sizeof(int);
+                    eventPayload[0].DataPointer = ((IntPtr)(&OriginatingTaskSchedulerID));
+                    eventPayload[0].Reserved = 0;
+                    eventPayload[1].Size = sizeof(int);
+                    eventPayload[1].DataPointer = ((IntPtr)(&OriginatingTaskID));
+                    eventPayload[1].Reserved = 0;
+                    eventPayload[2].Size = sizeof(int);
+                    eventPayload[2].DataPointer = ((IntPtr)(&TaskID));
+                    eventPayload[2].Reserved = 0;
+                    eventPayload[3].Size = sizeof(int);
+                    eventPayload[3].DataPointer = ((IntPtr)(&isExceptionalInt));
+                    eventPayload[3].Reserved = 0;
+                    WriteEventCore(TASKCOMPLETED_ID, 4, eventPayload);
+                }
+            }
+        }
+        #endregion
+
+        #region TaskWaitBegin
+        /// <summary>
+        /// Fired when starting to wait for a taks's completion explicitly or implicitly.
+        /// </summary>
+        /// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param>
+        /// <param name="OriginatingTaskID">The task ID.</param>
+        /// <param name="TaskID">The task ID.</param>
+        /// <param name="Behavior">Configured behavior for the wait.</param>
+        /// <param name="ContinueWithTaskID">
+        /// If known, if 'TaskID' has a 'continueWith' task, mention give its ID here.  
+        /// 0 means unknown.   This allows better visualization of the common sequential chaining case.
+        /// </param>
+        [Event(TASKWAITBEGIN_ID, Version = 3, Task = TplEtwProvider.Tasks.TaskWait, Opcode = EventOpcode.Send,
+         Level = EventLevel.Informational, Keywords = Keywords.TaskTransfer | Keywords.Tasks)]
+        public void TaskWaitBegin(
+            int OriginatingTaskSchedulerID, int OriginatingTaskID,  // PFX_COMMON_EVENT_HEADER
+            int TaskID, TaskWaitBehavior Behavior, int ContinueWithTaskID)
+        {
+            if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.TaskTransfer | Keywords.Tasks))
+            {
+                unsafe
+                {
+                    EventData* eventPayload = stackalloc EventData[5];
+                    eventPayload[0].Size = sizeof(int);
+                    eventPayload[0].DataPointer = ((IntPtr)(&OriginatingTaskSchedulerID));
+                    eventPayload[0].Reserved = 0;
+                    eventPayload[1].Size = sizeof(int);
+                    eventPayload[1].DataPointer = ((IntPtr)(&OriginatingTaskID));
+                    eventPayload[1].Reserved = 0;
+                    eventPayload[2].Size = sizeof(int);
+                    eventPayload[2].DataPointer = ((IntPtr)(&TaskID));
+                    eventPayload[2].Reserved = 0;
+                    eventPayload[3].Size = sizeof(int);
+                    eventPayload[3].DataPointer = ((IntPtr)(&Behavior));
+                    eventPayload[3].Reserved = 0;
+                    eventPayload[4].Size = sizeof(int);
+                    eventPayload[4].DataPointer = ((IntPtr)(&ContinueWithTaskID));
+                    eventPayload[4].Reserved = 0;
+                    if (TasksSetActivityIds)
+                    {
+                        Guid childActivityId = CreateGuidForTaskID(TaskID);
+                        WriteEventWithRelatedActivityIdCore(TASKWAITBEGIN_ID, &childActivityId, 5, eventPayload);
+                    }
+                    else
+                    {
+                        WriteEventCore(TASKWAITBEGIN_ID, 5, eventPayload);
+                    }
+                }
+            }
+        }
+        #endregion
+
+        /// <summary>
+        /// Fired when the wait for a tasks completion returns.
+        /// </summary>
+        /// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param>
+        /// <param name="OriginatingTaskID">The task ID.</param>
+        /// <param name="TaskID">The task ID.</param>
+        [Event(TASKWAITEND_ID,
+         Level = EventLevel.Verbose, Keywords = Keywords.Tasks)]
+        public void TaskWaitEnd(
+            int OriginatingTaskSchedulerID, int OriginatingTaskID,  // PFX_COMMON_EVENT_HEADER
+            int TaskID)
+        {
+            // Log an event if indicated.  
+            if (IsEnabled() && IsEnabled(EventLevel.Verbose, Keywords.Tasks))
+                WriteEvent(TASKWAITEND_ID, OriginatingTaskSchedulerID, OriginatingTaskID, TaskID);
+        }
+
+        /// <summary>
+        /// Fired when the work (method) associated with a TaskWaitEnd completes
+        /// </summary>
+        /// <param name="TaskID">The task ID.</param>
+        [Event(TASKWAITCONTINUATIONCOMPLETE_ID,
+         Level = EventLevel.Verbose, Keywords = Keywords.TaskStops)]
+        public void TaskWaitContinuationComplete(int TaskID)
+        {
+            // Log an event if indicated.  
+            if (IsEnabled() && IsEnabled(EventLevel.Verbose, Keywords.Tasks))
+                WriteEvent(TASKWAITCONTINUATIONCOMPLETE_ID, TaskID);
+        }
+
+        /// <summary>
+        /// Fired when the work (method) associated with a TaskWaitEnd completes
+        /// </summary>
+        /// <param name="TaskID">The task ID.</param>
+        [Event(TASKWAITCONTINUATIONSTARTED_ID,
+         Level = EventLevel.Verbose, Keywords = Keywords.TaskStops)]
+        public void TaskWaitContinuationStarted(int TaskID)
+        {
+            // Log an event if indicated.  
+            if (IsEnabled() && IsEnabled(EventLevel.Verbose, Keywords.Tasks))
+                WriteEvent(TASKWAITCONTINUATIONSTARTED_ID, TaskID);
+        }
+
+        /// <summary>
+        /// Fired when the an asynchronous continuation for a task is scheduled
+        /// </summary>
+        /// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param>
+        /// <param name="OriginatingTaskID">The task ID.</param>
+        [Event(AWAITTASKCONTINUATIONSCHEDULED_ID, Task = Tasks.AwaitTaskContinuationScheduled, Opcode = EventOpcode.Send,
+         Level = EventLevel.Informational, Keywords = Keywords.TaskTransfer | Keywords.Tasks)]
+        public void AwaitTaskContinuationScheduled(
+            int OriginatingTaskSchedulerID, int OriginatingTaskID,  // PFX_COMMON_EVENT_HEADER
+            int ContinuwWithTaskId)
+        {
+            if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.TaskTransfer | Keywords.Tasks))
+            {
+                unsafe
+                {
+                    EventData* eventPayload = stackalloc EventData[3];
+                    eventPayload[0].Size = sizeof(int);
+                    eventPayload[0].DataPointer = ((IntPtr)(&OriginatingTaskSchedulerID));
+                    eventPayload[0].Reserved = 0;
+                    eventPayload[1].Size = sizeof(int);
+                    eventPayload[1].DataPointer = ((IntPtr)(&OriginatingTaskID));
+                    eventPayload[1].Reserved = 0;
+                    eventPayload[2].Size = sizeof(int);
+                    eventPayload[2].DataPointer = ((IntPtr)(&ContinuwWithTaskId));
+                    eventPayload[2].Reserved = 0;
+                    if (TasksSetActivityIds)
+                    {
+                        Guid continuationActivityId = CreateGuidForTaskID(ContinuwWithTaskId);
+                        WriteEventWithRelatedActivityIdCore(AWAITTASKCONTINUATIONSCHEDULED_ID, &continuationActivityId, 3, eventPayload);
+                    }
+                    else
+                        WriteEventCore(AWAITTASKCONTINUATIONSCHEDULED_ID, 3, eventPayload);
+                }
+            }
+        }
+
+        [Event(TRACEOPERATIONSTART_ID, Version = 1,
+         Level = EventLevel.Informational, Keywords = Keywords.AsyncCausalityOperation)]
+        public void TraceOperationBegin(int TaskID, string OperationName, long RelatedContext)
+        {
+            if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.AsyncCausalityOperation))
+            {
+                unsafe
+                {
+                    fixed (char* operationNamePtr = OperationName)
+                    {
+                        EventData* eventPayload = stackalloc EventData[3];
+                        eventPayload[0].Size = sizeof(int);
+                        eventPayload[0].DataPointer = ((IntPtr)(&TaskID));
+                        eventPayload[0].Reserved = 0;
+
+                        eventPayload[1].Size = ((OperationName.Length + 1) * 2);
+                        eventPayload[1].DataPointer = ((IntPtr)operationNamePtr);
+                        eventPayload[1].Reserved = 0;
+
+                        eventPayload[2].Size = sizeof(long);
+                        eventPayload[2].DataPointer = ((IntPtr)(&RelatedContext));
+                        eventPayload[2].Reserved = 0;
+                        WriteEventCore(TRACEOPERATIONSTART_ID, 3, eventPayload);
+                    }
+                }
+            }
+        }
+#if !MONO
+        [Event(TRACEOPERATIONRELATION_ID, Version = 1,
+         Level = EventLevel.Informational, Keywords = Keywords.AsyncCausalityRelation)]
+        public void TraceOperationRelation(int TaskID, CausalityRelation Relation)
+        {
+            if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.AsyncCausalityRelation))
+                WriteEvent(TRACEOPERATIONRELATION_ID, TaskID, (int)Relation);                // optmized overload for this exists
+        }
+
+        [Event(TRACEOPERATIONSTOP_ID, Version = 1,
+         Level = EventLevel.Informational, Keywords = Keywords.AsyncCausalityOperation)]
+        public void TraceOperationEnd(int TaskID, AsyncCausalityStatus Status)
+        {
+            if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.AsyncCausalityOperation))
+                WriteEvent(TRACEOPERATIONSTOP_ID, TaskID, (int)Status);                     // optmized overload for this exists
+        }
+
+        [Event(TRACESYNCHRONOUSWORKSTART_ID, Version = 1,
+         Level = EventLevel.Informational, Keywords = Keywords.AsyncCausalitySynchronousWork)]
+        public void TraceSynchronousWorkBegin(int TaskID, CausalitySynchronousWork Work)
+        {
+            if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.AsyncCausalitySynchronousWork))
+                WriteEvent(TRACESYNCHRONOUSWORKSTART_ID, TaskID, (int)Work);               // optmized overload for this exists
+        }
+
+        [Event(TRACESYNCHRONOUSWORKSTOP_ID, Version = 1,
+         Level = EventLevel.Informational, Keywords = Keywords.AsyncCausalitySynchronousWork)]
+        public void TraceSynchronousWorkEnd(CausalitySynchronousWork Work)
+        {
+            if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.AsyncCausalitySynchronousWork))
+            {
+                unsafe
+                {
+                    EventData* eventPayload = stackalloc EventData[1];
+                    eventPayload[0].Size = sizeof(int);
+                    eventPayload[0].DataPointer = ((IntPtr)(&Work));
+                    eventPayload[0].Reserved = 0;
+
+                    WriteEventCore(TRACESYNCHRONOUSWORKSTOP_ID, 1, eventPayload);
+                }
+            }
+        }
+#endif
+        [NonEvent]
+        public unsafe void RunningContinuation(int TaskID, object Object) { RunningContinuation(TaskID, (long)*((void**)Unsafe.AsPointer(ref Object))); }
+        [Event(20, Keywords = Keywords.Debug)]
+        private void RunningContinuation(int TaskID, long Object)
+        {
+            if (Debug)
+                WriteEvent(20, TaskID, Object);
+        }
+
+        [NonEvent]
+        public unsafe void RunningContinuationList(int TaskID, int Index, object Object) { RunningContinuationList(TaskID, Index, (long)*((void**)Unsafe.AsPointer(ref Object))); }
+
+        [Event(21, Keywords = Keywords.Debug)]
+        public void RunningContinuationList(int TaskID, int Index, long Object)
+        {
+            if (Debug)
+                WriteEvent(21, TaskID, Index, Object);
+        }
+
+        [Event(23, Keywords = Keywords.Debug)]
+        public void DebugFacilityMessage(string Facility, string Message) { WriteEvent(23, Facility, Message); }
+
+        [Event(24, Keywords = Keywords.Debug)]
+        public void DebugFacilityMessage1(string Facility, string Message, string Value1) { WriteEvent(24, Facility, Message, Value1); }
+
+        [Event(25, Keywords = Keywords.DebugActivityId)]
+        public void SetActivityId(Guid NewId)
+        {
+            if (DebugActivityId)
+                WriteEvent(25, NewId);
+        }
+
+        [Event(26, Keywords = Keywords.Debug)]
+        public void NewID(int TaskID)
+        {
+            if (Debug)
+                WriteEvent(26, TaskID);
+        }
+
+        [NonEvent]
+        public void IncompleteAsyncMethod(IAsyncStateMachineBox stateMachineBox)
+        {
+            System.Diagnostics.Debug.Assert(stateMachineBox != null);
+            if (IsEnabled(EventLevel.Warning, Keywords.AsyncMethod))
+            {
+                IAsyncStateMachine stateMachine = stateMachineBox.GetStateMachineObject();
+                if (stateMachine != null)
+                {
+                    string description = AsyncMethodBuilderCore.GetAsyncStateMachineDescription(stateMachine);
+                    IncompleteAsyncMethod(description);
+                }
+            }
+        }
+
+        [Event(27, Level = EventLevel.Warning, Keywords = Keywords.AsyncMethod)]
+        private void IncompleteAsyncMethod(string stateMachineDescription) =>
+            WriteEvent(27, stateMachineDescription);
+
+        /// <summary>
+        /// Activity IDs are GUIDS but task IDS are integers (and are not unique across appdomains
+        /// This routine creates a process wide unique GUID given a task ID
+        /// </summary>
+        internal static Guid CreateGuidForTaskID(int taskID)
+        {
+            // The thread pool generated a process wide unique GUID from a task GUID by
+            // using the taskGuid, the appdomain ID, and 8 bytes of 'randomization' chosen by
+            // using the last 8 bytes  as the provider GUID for this provider.  
+            // These were generated by CreateGuid, and are reasonably random (and thus unlikley to collide
+            uint pid = EventSource.s_currentPid;
+            int appDomainID = System.Threading.Thread.GetDomainID();
+            return new Guid(taskID,
+                            (short)appDomainID, (short)(appDomainID >> 16),
+                            (byte)pid, (byte)(pid >> 8), (byte)(pid >> 16), (byte)(pid >> 24),
+                            0xff, 0xdc, 0xd7, 0xb5);
+        }
+    }
+}

+ 6555 - 0
mcs/class/System.Private.CoreLib/temp/Task.cs

@@ -0,0 +1,6555 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
+//
+//
+//
+// A schedulable unit of work.
+//
+// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
+
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.Diagnostics;
+using System.Runtime.CompilerServices;
+using System.Runtime.ExceptionServices;
+
+//using Internal.Threading.Tasks.Tracing;
+
+using AsyncStatus = Internal.Runtime.Augments.AsyncStatus;
+using CausalityRelation = Internal.Runtime.Augments.CausalityRelation;
+using CausalitySource = Internal.Runtime.Augments.CausalitySource;
+using CausalitySynchronousWork = Internal.Runtime.Augments.CausalitySynchronousWork;
+using CausalityTraceLevel = Internal.Runtime.Augments.CausalityTraceLevel;
+using Thread = Internal.Runtime.Augments.RuntimeThread;
+
+// Disable the "reference to volatile field not treated as volatile" error.
+#pragma warning disable 0420
+
+namespace System.Threading.Tasks
+{
+    /// <summary>
+    /// Utility class for allocating structs as heap variables
+    /// </summary>
+    internal class Shared<T>
+    {
+        internal T Value;
+
+        internal Shared(T value)
+        {
+            this.Value = value;
+        }
+    }
+
+    /// <summary>
+    /// Represents the current stage in the lifecycle of a <see cref="Task"/>.
+    /// </summary>
+    public enum TaskStatus
+    {
+        /// <summary> 
+        /// The task has been initialized but has not yet been scheduled.
+        /// </summary>
+        Created,
+        /// <summary> 
+        /// The task is waiting to be activated and scheduled internally by the .NET Framework infrastructure.
+        /// </summary>
+        WaitingForActivation,
+        /// <summary>
+        /// The task has been scheduled for execution but has not yet begun executing.
+        /// </summary>
+        WaitingToRun,
+        /// <summary>
+        /// The task is running but has not yet completed.
+        /// </summary>
+        Running,
+        // /// <summary>
+        // /// The task is currently blocked in a wait state.
+        // /// </summary>
+        // Blocked,
+        /// <summary>
+        /// The task has finished executing and is implicitly waiting for
+        /// attached child tasks to complete.
+        /// </summary>
+        WaitingForChildrenToComplete,
+        /// <summary>
+        /// The task completed execution successfully.
+        /// </summary>
+        RanToCompletion,
+        /// <summary>
+        /// The task acknowledged cancellation by throwing an OperationCanceledException with its own CancellationToken
+        /// while the token was in signaled state, or the task's CancellationToken was already signaled before the
+        /// task started executing.
+        /// </summary>
+        Canceled,
+        /// <summary>
+        /// The task completed due to an unhandled exception.
+        /// </summary>
+        Faulted
+    }
+
+    /// <summary>
+    /// Represents an asynchronous operation.
+    /// </summary>
+    /// <remarks>
+    /// <para>
+    /// <see cref="Task"/> instances may be created in a variety of ways. The most common approach is by
+    /// using the Task type's <see cref="Factory"/> property to retrieve a <see
+    /// cref="System.Threading.Tasks.TaskFactory"/> instance that can be used to create tasks for several
+    /// purposes. For example, to create a <see cref="Task"/> that runs an action, the factory's StartNew
+    /// method may be used:
+    /// <code>
+    /// // C# 
+    /// var t = Task.Factory.StartNew(() => DoAction());
+    /// 
+    /// ' Visual Basic 
+    /// Dim t = Task.Factory.StartNew(Function() DoAction())
+    /// </code>
+    /// </para>
+    /// <para>
+    /// The <see cref="Task"/> class also provides constructors that initialize the Task but that do not
+    /// schedule it for execution. For performance reasons, TaskFactory's StartNew method should be the
+    /// preferred mechanism for creating and scheduling computational tasks, but for scenarios where creation
+    /// and scheduling must be separated, the constructors may be used, and the task's <see cref="Start()"/>
+    /// method may then be used to schedule the task for execution at a later time.
+    /// </para>
+    /// <para>
+    /// All members of <see cref="Task"/>, except for <see cref="Dispose()"/>, are thread-safe
+    /// and may be used from multiple threads concurrently.
+    /// </para>
+    /// <para>
+    /// For operations that return values, the <see cref="System.Threading.Tasks.Task{TResult}"/> class
+    /// should be used.
+    /// </para>
+    /// <para>
+    /// For developers implementing custom debuggers, several internal and private members of Task may be
+    /// useful (these may change from release to release). The Int32 m_taskId field serves as the backing
+    /// store for the <see cref="Id"/> property, however accessing this field directly from a debugger may be
+    /// more efficient than accessing the same value through the property's getter method (the
+    /// s_taskIdCounter Int32 counter is used to retrieve the next available ID for a Task). Similarly, the
+    /// Int32 m_stateFlags field stores information about the current lifecycle stage of the Task,
+    /// information also accessible through the <see cref="Status"/> property. The m_action System.Object
+    /// field stores a reference to the Task's delegate, and the m_stateObject System.Object field stores the
+    /// async state passed to the Task by the developer. Finally, for debuggers that parse stack frames, the
+    /// InternalWait method serves a potential marker for when a Task is entering a wait operation.
+    /// </para>
+    /// </remarks>
+    [DebuggerTypeProxy(typeof(SystemThreadingTasks_TaskDebugView))]
+    [DebuggerDisplay("Id = {Id}, Status = {Status}, Method = {DebuggerDisplayMethodDescription}")]
+    public class Task : IAsyncResult, IDisposable
+    {
+
+        internal static int NewId() => 0;
+
+        [ThreadStatic]
+        internal static Task t_currentTask;  // The currently executing task.
+        [ThreadStatic]
+        private static StackGuard t_stackGuard;  // The stack guard object for this thread
+
+        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
+
+        internal Delegate m_action;    // The body of the task.  Might be Action<object>, Action<TState> or Action.  Or possibly a Func.
+        // If m_action is set to null it will indicate that we operate in the
+        // "externally triggered completion" mode, which is exclusively meant 
+        // for the signalling Task<TResult> (aka. promise). In this mode,
+        // we don't call InnerInvoke() in response to a Wait(), but simply wait on
+        // the completion event which will be set when the Future class calls Finish().
+        // But the event would now be signalled if Cancel() is called
+
+
+        internal object m_stateObject; // A state object that can be optionally supplied, passed to action.
+        internal TaskScheduler m_taskScheduler; // The task scheduler this task runs under. 
+
+        internal volatile int m_stateFlags; // SOS DumpAsync command depends on this name
+
+        private Task ParentForDebugger => m_contingentProperties?.m_parent; // Private property used by a debugger to access this Task's parent
+        private int StateFlagsForDebugger => m_stateFlags; // Private property used by a debugger to access this Task's state flags
+
+        // State constants for m_stateFlags;
+        // The bits of m_stateFlags are allocated as follows:
+        //   0x40000000 - TaskBase state flag
+        //   0x3FFF0000 - Task state flags
+        //   0x0000FF00 - internal TaskCreationOptions flags
+        //   0x000000FF - publicly exposed TaskCreationOptions flags
+        //
+        // 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_THREAD_WAS_ABORTED = 0x8000000;                          //bin: 0000 1000 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.
+        private const int TASK_STATE_COMPLETED_MASK = TASK_STATE_CANCELED | TASK_STATE_FAULTED | TASK_STATE_RAN_TO_COMPLETION;
+
+        // Values for ContingentProperties.m_internalCancellationRequested.
+        private const int CANCELLATION_REQUESTED = 0x1;
+
+        // Can be null, a single continuation, a list of continuations, or s_taskCompletionSentinel,
+        // in that order. The logic arround this object assumes it will never regress to a previous state.
+        private volatile object m_continuationObject = null; // SOS DumpAsync command depends on this name
+
+        // m_continuationObject is set to this when the task completes.
+        private static readonly object s_taskCompletionSentinel = new object();
+
+#pragma warning disable 0649   // Yes, C#, we know that s_asyncDebuggingEnabled is never assigned to by code...
+        // 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
+#pragma warning restore 0649
+
+        // 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.
+        private static readonly Dictionary<int, Task> s_currentActiveTasks = new Dictionary<int, Task>();
+        private static readonly object s_activeTasksLock = new object();
+
+        // These methods are a way to access the dictionary both from this class and for other classes that also
+        // activate dummy tasks. Specifically the AsyncTaskMethodBuilder and AsyncTaskMethodBuilder<>
+        internal static bool AddToActiveTasks(Task task)
+        {
+            Debug.Assert(task != null, "Null Task objects can't be added to the ActiveTasks collection");
+            lock (s_activeTasksLock)
+            {
+                s_currentActiveTasks[task.Id] = task;
+            }
+            //always return true to keep signature as bool for backwards compatibility
+            return true;
+        }
+
+        internal static void RemoveFromActiveTasks(int taskId)
+        {
+            lock (s_activeTasksLock)
+            {
+                s_currentActiveTasks.Remove(taskId);
+            }
+        }
+
+        // We moved a number of Task properties into this class.  The idea is that in most cases, these properties never
+        // need to be accessed during the life cycle of a Task, so we don't want to instantiate them every time.  Once
+        // one of these properties needs to be written, we will instantiate a ContingentProperties object and set
+        // the appropriate property.
+        internal class ContingentProperties
+        {
+            // Additional context
+
+            internal ExecutionContext m_capturedContext; // The execution context to run the task within, if any. Only set from non-concurrent contexts.
+
+            // Completion fields (exceptions and event)
+
+            internal volatile ManualResetEventSlim m_completionEvent; // Lazily created if waiting is required.
+            internal volatile TaskExceptionHolder m_exceptionsHolder; // Tracks exceptions, if any have occurred
+
+            // Cancellation fields (token, registration, and internally requested)
+
+            internal CancellationToken m_cancellationToken; // Task's cancellation token, if it has one
+            internal Shared<CancellationTokenRegistration> m_cancellationRegistration; // Task's registration with the cancellation token
+            internal volatile int m_internalCancellationRequested; // Its own field because multiple threads legally try to set it.
+
+            // Parenting fields
+
+            // # of active children + 1 (for this task itself).
+            // Used for ensuring all children are done before this task can complete
+            // The extra count helps prevent the race condition for executing the final state transition
+            // (i.e. whether the last child or this task itself should call FinishStageTwo())
+            internal volatile int m_completionCountdown = 1;
+            // A list of child tasks that threw an exception (TCEs don't count),
+            // but haven't yet been waited on by the parent, lazily initialized.
+            internal volatile List<Task> m_exceptionalChildren;
+            // A task's parent, or null if parent-less. Only set during Task construction.
+            internal Task m_parent;
+
+            /// <summary>
+            /// Sets the internal completion event.
+            /// </summary>
+            internal void SetCompleted()
+            {
+                var mres = m_completionEvent;
+                if (mres != null) mres.Set();
+            }
+
+            /// <summary>
+            /// Checks if we registered a CT callback during construction, and unregisters it.
+            /// This should be called when we know the registration isn't useful anymore. Specifically from Finish() if the task has completed
+            /// successfully or with an exception.
+            /// </summary>
+            internal void UnregisterCancellationCallback()
+            {
+                if (m_cancellationRegistration != null)
+                {
+                    // Harden against ODEs thrown from disposing of the CTR.
+                    // Since the task has already been put into a final state by the time this
+                    // is called, all we can do here is suppress the exception.
+                    try { m_cancellationRegistration.Value.Dispose(); }
+                    catch (ObjectDisposedException) { }
+                    m_cancellationRegistration = null;
+                }
+            }
+        }
+
+
+        // This field will only be instantiated to some non-null value if any ContingentProperties need to be set.
+        // This will be a ContingentProperties instance or a type derived from it
+        internal ContingentProperties m_contingentProperties;
+
+        // Special internal constructor to create an already-completed task.
+        // if canceled==true, create a Canceled task, or else create a RanToCompletion task.
+        // Constructs the task as already completed
+        internal Task(bool canceled, TaskCreationOptions creationOptions, CancellationToken ct)
+        {
+            int optionFlags = (int)creationOptions;
+            if (canceled)
+            {
+                m_stateFlags = TASK_STATE_CANCELED | TASK_STATE_CANCELLATIONACKNOWLEDGED | optionFlags;
+                m_contingentProperties = new ContingentProperties() // can't have children, so just instantiate directly
+                {
+                    m_cancellationToken = ct,
+                    m_internalCancellationRequested = CANCELLATION_REQUESTED,
+                };
+            }
+            else
+                m_stateFlags = TASK_STATE_RAN_TO_COMPLETION | optionFlags;
+        }
+
+        /// <summary>Constructor for use with promise-style tasks that aren't configurable.</summary>
+        internal Task()
+        {
+            m_stateFlags = TASK_STATE_WAITINGFORACTIVATION | (int)InternalTaskOptions.PromiseTask;
+        }
+
+        // Special constructor for use with promise-style tasks.
+        // Added promiseStyle parameter as an aid to the compiler to distinguish between (state,TCO) and
+        // (action,TCO).  It should always be true.
+        internal Task(object state, TaskCreationOptions creationOptions, bool promiseStyle)
+        {
+            Debug.Assert(promiseStyle, "Promise CTOR: promiseStyle was false");
+
+            // Check the creationOptions. We allow the AttachedToParent option to be specified for promise tasks.
+            // Also allow RunContinuationsAsynchronously because this is the constructor called by TCS
+            if ((creationOptions & ~(TaskCreationOptions.AttachedToParent | TaskCreationOptions.RunContinuationsAsynchronously)) != 0)
+            {
+                ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.creationOptions);
+            }
+
+            // Only set a parent if AttachedToParent is specified.
+            if ((creationOptions & TaskCreationOptions.AttachedToParent) != 0)
+            {
+                Task parent = Task.InternalCurrent;
+                if (parent != null)
+                {
+                    EnsureContingentPropertiesInitializedUnsafe().m_parent = parent;
+                }
+            }
+
+            TaskConstructorCore(null, state, default, creationOptions, InternalTaskOptions.PromiseTask, null);
+        }
+
+        /// <summary>
+        /// Initializes a new <see cref="Task"/> with the specified action.
+        /// </summary>
+        /// <param name="action">The delegate that represents the code to execute in the Task.</param>
+        /// <exception cref="T:System.ArgumentNullException">The <paramref name="action"/> argument is null.</exception>
+        public Task(Action action)
+            : this(action, null, null, default, TaskCreationOptions.None, InternalTaskOptions.None, null)
+        {
+        }
+
+        /// <summary>
+        /// Initializes a new <see cref="Task"/> with the specified action and <see cref="System.Threading.CancellationToken">CancellationToken</see>.
+        /// </summary>
+        /// <param name="action">The delegate that represents the code to execute in the Task.</param>
+        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken">CancellationToken</see>
+        /// that will be assigned to the new Task.</param>
+        /// <exception cref="T:System.ArgumentNullException">The <paramref name="action"/> argument is null.</exception>
+        /// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
+        /// has already been disposed.
+        /// </exception>
+        public Task(Action action, CancellationToken cancellationToken)
+            : this(action, null, null, cancellationToken, TaskCreationOptions.None, InternalTaskOptions.None, null)
+        {
+        }
+
+        /// <summary>
+        /// Initializes a new <see cref="Task"/> with the specified action and creation options.
+        /// </summary>
+        /// <param name="action">The delegate that represents the code to execute in the task.</param>
+        /// <param name="creationOptions">
+        /// The <see cref="System.Threading.Tasks.TaskCreationOptions">TaskCreationOptions</see> used to
+        /// customize the Task's behavior.
+        /// </param>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="action"/> argument is null.
+        /// </exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">
+        /// The <paramref name="creationOptions"/> argument specifies an invalid value for <see
+        /// cref="T:System.Threading.Tasks.TaskCreationOptions"/>.
+        /// </exception>
+        public Task(Action action, TaskCreationOptions creationOptions)
+            : this(action, null, Task.InternalCurrentIfAttached(creationOptions), default, creationOptions, InternalTaskOptions.None, null)
+        {
+        }
+
+        /// <summary>
+        /// Initializes a new <see cref="Task"/> with the specified action and creation options.
+        /// </summary>
+        /// <param name="action">The delegate that represents the code to execute in the task.</param>
+        /// <param name="cancellationToken">The <see cref="CancellationToken"/> that will be assigned to the new task.</param>
+        /// <param name="creationOptions">
+        /// The <see cref="System.Threading.Tasks.TaskCreationOptions">TaskCreationOptions</see> used to
+        /// customize the Task's behavior.
+        /// </param>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="action"/> argument is null.
+        /// </exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">
+        /// The <paramref name="creationOptions"/> argument specifies an invalid value for <see
+        /// cref="T:System.Threading.Tasks.TaskCreationOptions"/>.
+        /// </exception>
+        /// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
+        /// has already been disposed.
+        /// </exception>
+        public Task(Action action, CancellationToken cancellationToken, TaskCreationOptions creationOptions)
+            : this(action, null, Task.InternalCurrentIfAttached(creationOptions), cancellationToken, creationOptions, InternalTaskOptions.None, null)
+        {
+        }
+
+
+        /// <summary>
+        /// Initializes a new <see cref="Task"/> with the specified action and state.
+        /// </summary>
+        /// <param name="action">The delegate that represents the code to execute in the task.</param>
+        /// <param name="state">An object representing data to be used by the action.</param>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="action"/> argument is null.
+        /// </exception>
+        public Task(Action<object> action, object state)
+            : this(action, state, null, default, TaskCreationOptions.None, InternalTaskOptions.None, null)
+        {
+        }
+
+        /// <summary>
+        /// Initializes a new <see cref="Task"/> with the specified action, state, and options.
+        /// </summary>
+        /// <param name="action">The delegate that represents the code to execute in the task.</param>
+        /// <param name="state">An object representing data to be used by the action.</param>
+        /// <param name="cancellationToken">The <see cref="CancellationToken"/> that will be assigned to the new task.</param>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="action"/> argument is null.
+        /// </exception>
+        /// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
+        /// has already been disposed.
+        /// </exception>
+        public Task(Action<object> action, object state, CancellationToken cancellationToken)
+            : this(action, state, null, cancellationToken, TaskCreationOptions.None, InternalTaskOptions.None, null)
+        {
+        }
+
+        /// <summary>
+        /// Initializes a new <see cref="Task"/> with the specified action, state, and options.
+        /// </summary>
+        /// <param name="action">The delegate that represents the code to execute in the task.</param>
+        /// <param name="state">An object representing data to be used by the action.</param>
+        /// <param name="creationOptions">
+        /// The <see cref="System.Threading.Tasks.TaskCreationOptions">TaskCreationOptions</see> used to
+        /// customize the Task's behavior.
+        /// </param>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="action"/> argument is null.
+        /// </exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">
+        /// The <paramref name="creationOptions"/> argument specifies an invalid value for <see
+        /// cref="T:System.Threading.Tasks.TaskCreationOptions"/>.
+        /// </exception>
+        public Task(Action<object> action, object state, TaskCreationOptions creationOptions)
+            : this(action, state, Task.InternalCurrentIfAttached(creationOptions), default, creationOptions, InternalTaskOptions.None, null)
+        {
+        }
+
+        /// <summary>
+        /// Initializes a new <see cref="Task"/> with the specified action, state, and options.
+        /// </summary>
+        /// <param name="action">The delegate that represents the code to execute in the task.</param>
+        /// <param name="state">An object representing data to be used by the action.</param>
+        /// <param name="cancellationToken">The <see cref="CancellationToken"/> that will be assigned to the new task.</param>
+        /// <param name="creationOptions">
+        /// The <see cref="System.Threading.Tasks.TaskCreationOptions">TaskCreationOptions</see> used to
+        /// customize the Task's behavior.
+        /// </param>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="action"/> argument is null.
+        /// </exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">
+        /// The <paramref name="creationOptions"/> argument specifies an invalid value for <see
+        /// cref="T:System.Threading.Tasks.TaskCreationOptions"/>.
+        /// </exception>
+        /// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
+        /// has already been disposed.
+        /// </exception>
+        public Task(Action<object> action, object state, CancellationToken cancellationToken, TaskCreationOptions creationOptions)
+            : this(action, state, Task.InternalCurrentIfAttached(creationOptions), cancellationToken, creationOptions, InternalTaskOptions.None, null)
+        {
+        }
+
+        /// <summary>
+        /// An internal constructor used by the factory methods on task and its descendent(s).
+        /// </summary>
+        /// <param name="action">An action to execute.</param>
+        /// <param name="state">Optional state to pass to the action.</param>
+        /// <param name="parent">Parent of Task.</param>
+        /// <param name="cancellationToken">A CancellationToken for the task.</param>
+        /// <param name="scheduler">A task scheduler under which the task will run.</param>
+        /// <param name="creationOptions">Options to control its execution.</param>
+        /// <param name="internalOptions">Internal options to control its execution</param>
+        internal Task(Delegate action, object state, Task parent, CancellationToken cancellationToken,
+            TaskCreationOptions creationOptions, InternalTaskOptions internalOptions, TaskScheduler scheduler)
+        {
+            if (action == null)
+            {
+                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.action);
+            }
+
+            // Keep a link to the parent if attached
+            if (parent != null && (creationOptions & TaskCreationOptions.AttachedToParent) != 0)
+            {
+                EnsureContingentPropertiesInitializedUnsafe().m_parent = parent;
+            }
+
+            TaskConstructorCore(action, state, cancellationToken, creationOptions, internalOptions, scheduler);
+        }
+
+        /// <summary>
+        /// Common logic used by the following internal ctors:
+        ///     Task()
+        ///     Task(object action, object state, Task parent, TaskCreationOptions options, TaskScheduler taskScheduler)
+        /// </summary>
+        /// <param name="action">Action for task to execute.</param>
+        /// <param name="state">Object to which to pass to action (may be null)</param>
+        /// <param name="scheduler">Task scheduler on which to run thread (only used by continuation tasks).</param>
+        /// <param name="cancellationToken">A CancellationToken for the Task.</param>
+        /// <param name="creationOptions">Options to customize behavior of Task.</param>
+        /// <param name="internalOptions">Internal options to customize behavior of Task.</param>
+        internal void TaskConstructorCore(Delegate action, object state, CancellationToken cancellationToken,
+            TaskCreationOptions creationOptions, InternalTaskOptions internalOptions, TaskScheduler scheduler)
+        {
+            m_action = action;
+            m_stateObject = state;
+            m_taskScheduler = scheduler;
+
+            // Check for validity of options
+            if ((creationOptions &
+                    ~(TaskCreationOptions.AttachedToParent |
+                      TaskCreationOptions.LongRunning |
+                      TaskCreationOptions.DenyChildAttach |
+                      TaskCreationOptions.HideScheduler |
+                      TaskCreationOptions.PreferFairness |
+                      TaskCreationOptions.RunContinuationsAsynchronously)) != 0)
+            {
+                ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.creationOptions);
+            }
+
+#if DEBUG
+            // Check the validity of internalOptions
+            int illegalInternalOptions =
+                    (int)(internalOptions &
+                            ~(InternalTaskOptions.PromiseTask |
+                              InternalTaskOptions.ContinuationTask |
+                              InternalTaskOptions.LazyCancellation |
+                              InternalTaskOptions.QueuedByRuntime));
+            Debug.Assert(illegalInternalOptions == 0, "TaskConstructorCore: Illegal internal options");
+#endif
+
+            // Assign options to m_stateAndOptionsFlag.
+            Debug.Assert(m_stateFlags == 0, "TaskConstructorCore: non-zero m_stateFlags");
+            Debug.Assert((((int)creationOptions) | OptionsMask) == OptionsMask, "TaskConstructorCore: options take too many bits");
+            int tmpFlags = (int)creationOptions | (int)internalOptions; // one write to the volatile m_stateFlags instead of two when setting the above options
+            m_stateFlags = m_action == null || (internalOptions & InternalTaskOptions.ContinuationTask) != 0 ?
+                tmpFlags | TASK_STATE_WAITINGFORACTIVATION :
+                tmpFlags;
+
+            // Now is the time to add the new task to the children list 
+            // of the creating task if the options call for it.
+            // We can safely call the creator task's AddNewChild() method to register it, 
+            // because at this point we are already on its thread of execution.
+
+            ContingentProperties props = m_contingentProperties;
+            if (props != null)
+            {
+                Task parent = props.m_parent;
+                if (parent != null
+                    && ((creationOptions & TaskCreationOptions.AttachedToParent) != 0)
+                    && ((parent.CreationOptions & TaskCreationOptions.DenyChildAttach) == 0))
+                {
+                    parent.AddNewChild();
+                }
+            }
+
+            // if we have a non-null cancellationToken, allocate the contingent properties to save it
+            // we need to do this as the very last thing in the construction path, because the CT registration could modify m_stateFlags
+            if (cancellationToken.CanBeCanceled)
+            {
+                Debug.Assert((internalOptions & InternalTaskOptions.ContinuationTask) == 0, "TaskConstructorCore: Did not expect to see cancelable token for continuation task.");
+
+                AssignCancellationToken(cancellationToken, null, null);
+            }
+
+            Debug.Assert(m_contingentProperties == null || m_contingentProperties.m_capturedContext == null,
+                "Captured an ExecutionContext when one was already captured.");
+            CapturedContext = ExecutionContext.Capture();
+        }
+
+        /// <summary>
+        /// Handles everything needed for associating a CancellationToken with a task which is being constructed.
+        /// This method is meant to be called either from the TaskConstructorCore or from ContinueWithCore.
+        /// </summary>
+        private void AssignCancellationToken(CancellationToken cancellationToken, Task antecedent, TaskContinuation continuation)
+        {
+            // There is no need to worry about concurrency issues here because we are in the constructor path of the task --
+            // there should not be any race conditions to set m_contingentProperties at this point.
+            ContingentProperties props = EnsureContingentPropertiesInitializedUnsafe();
+            props.m_cancellationToken = cancellationToken;
+
+            try
+            {
+                // If an unstarted task has a valid CancellationToken that gets signalled while the task is still not queued
+                // we need to proactively cancel it, because it may never execute to transition itself. 
+                // The only way to accomplish this is to register a callback on the CT.
+                // We exclude Promise tasks from this, because TaskCompletionSource needs to fully control the inner tasks's lifetime (i.e. not allow external cancellations)                
+                if ((((InternalTaskOptions)Options &
+                    (InternalTaskOptions.QueuedByRuntime | InternalTaskOptions.PromiseTask | InternalTaskOptions.LazyCancellation)) == 0))
+                {
+                    if (cancellationToken.IsCancellationRequested)
+                    {
+                        // Fast path for an already-canceled cancellationToken
+                        this.InternalCancel(false);
+                    }
+                    else
+                    {
+                        // Regular path for an uncanceled cancellationToken
+                        CancellationTokenRegistration ctr;
+                        if (antecedent == null)
+                        {
+                            // if no antecedent was specified, use this task's reference as the cancellation state object
+                            ctr = cancellationToken.UnsafeRegister(s_taskCancelCallback, this);
+                        }
+                        else
+                        {
+                            // If an antecedent was specified, pack this task, its antecedent and the TaskContinuation together as a tuple 
+                            // and use it as the cancellation state object. This will be unpacked in the cancellation callback so that 
+                            // antecedent.RemoveCancellation(continuation) can be invoked.
+                            ctr = cancellationToken.UnsafeRegister(s_taskCancelCallback,
+                                                                              new Tuple<Task, Task, TaskContinuation>(this, antecedent, continuation));
+                        }
+
+                        props.m_cancellationRegistration = new Shared<CancellationTokenRegistration>(ctr);
+                    }
+                }
+            }
+            catch
+            {
+                // If we have an exception related to our CancellationToken, then we need to subtract ourselves
+                // from our parent before throwing it.
+                Task parent = m_contingentProperties?.m_parent;
+                if ((parent != null) &&
+                    ((Options & TaskCreationOptions.AttachedToParent) != 0)
+                     && ((parent.Options & TaskCreationOptions.DenyChildAttach) == 0))
+                {
+                    parent.DisregardChild();
+                }
+                throw;
+            }
+        }
+
+
+        // Static delegate to be used as a cancellation callback on unstarted tasks that have a valid cancellation token.
+        // This is necessary to transition them into canceled state if their cancellation token is signalled while they are still not queued
+        private readonly static Action<object> s_taskCancelCallback = new Action<object>(TaskCancelCallback);
+        private static void TaskCancelCallback(object o)
+        {
+            var targetTask = o as Task;
+            if (targetTask == null)
+            {
+                var tuple = o as Tuple<Task, Task, TaskContinuation>;
+                if (tuple != null)
+                {
+                    targetTask = tuple.Item1;
+
+                    Task antecedentTask = tuple.Item2;
+                    TaskContinuation continuation = tuple.Item3;
+                    antecedentTask.RemoveContinuation(continuation);
+                }
+            }
+            Debug.Assert(targetTask != null,
+                "targetTask should have been non-null, with the supplied argument being a task or a tuple containing one");
+            targetTask.InternalCancel(false);
+        }
+
+        // Debugger support
+        private string DebuggerDisplayMethodDescription
+        {
+            get
+            {
+                Delegate d = m_action;
+                return d != null ? d.Method.ToString() : "{null}";
+            }
+        }
+
+        // Internal property to process TaskCreationOptions access and mutation.
+        internal TaskCreationOptions Options => OptionsMethod(m_stateFlags);
+
+        // Similar to Options property, but allows for the use of a cached flags value rather than
+        // a read of the volatile m_stateFlags field.
+        internal static TaskCreationOptions OptionsMethod(int flags)
+        {
+            Debug.Assert((OptionsMask & 1) == 1, "OptionsMask needs a shift in Options.get");
+            return (TaskCreationOptions)(flags & OptionsMask);
+        }
+
+        // Atomically OR-in newBits to m_stateFlags, while making sure that
+        // no illegalBits are set.  Returns true on success, false on failure.
+        internal bool AtomicStateUpdate(int newBits, int illegalBits)
+        {
+            int oldFlags = m_stateFlags;
+            return
+                (oldFlags & illegalBits) == 0 &&
+                (Interlocked.CompareExchange(ref m_stateFlags, oldFlags | newBits, oldFlags) == oldFlags ||
+                 AtomicStateUpdateSlow(newBits, illegalBits));
+        }
+
+        private bool AtomicStateUpdateSlow(int newBits, int illegalBits)
+        {
+            int flags = m_stateFlags;
+            do
+            {
+                if ((flags & illegalBits) != 0) return false;
+                int oldFlags = Interlocked.CompareExchange(ref m_stateFlags, flags | newBits, flags);
+                if (oldFlags == flags)
+                {
+                    return true;
+                }
+                flags = oldFlags;
+            } while (true);
+        }
+
+        internal bool AtomicStateUpdate(int newBits, int illegalBits, ref int oldFlags)
+        {
+            int flags = oldFlags = m_stateFlags;
+            do
+            {
+                if ((flags & illegalBits) != 0) return false;
+                oldFlags = Interlocked.CompareExchange(ref m_stateFlags, flags | newBits, flags);
+                if (oldFlags == flags)
+                {
+                    return true;
+                }
+                flags = oldFlags;
+            } while (true);
+        }
+
+        /// <summary>
+        /// Sets or clears the TASK_STATE_WAIT_COMPLETION_NOTIFICATION state bit.
+        /// The debugger sets this bit to aid it in "stepping out" of an async method body.
+        /// If enabled is true, this must only be called on a task that has not yet been completed.
+        /// If enabled is false, this may be called on completed tasks.
+        /// Either way, it should only be used for promise-style tasks.
+        /// </summary>
+        /// <param name="enabled">true to set the bit; false to unset the bit.</param>
+        internal void SetNotificationForWaitCompletion(bool enabled)
+        {
+            Debug.Assert((Options & (TaskCreationOptions)InternalTaskOptions.PromiseTask) != 0,
+                "Should only be used for promise-style tasks"); // hasn't been vetted on other kinds as there hasn't been a need
+
+            if (enabled)
+            {
+                // Atomically set the END_AWAIT_NOTIFICATION bit
+                bool success = AtomicStateUpdate(TASK_STATE_WAIT_COMPLETION_NOTIFICATION,
+                                  TASK_STATE_COMPLETED_MASK | TASK_STATE_COMPLETION_RESERVED);
+                Debug.Assert(success, "Tried to set enabled on completed Task");
+            }
+            else
+            {
+                // Atomically clear the END_AWAIT_NOTIFICATION bit
+                int flags = m_stateFlags;
+                while (true)
+                {
+                    int oldFlags = Interlocked.CompareExchange(ref m_stateFlags, flags & (~TASK_STATE_WAIT_COMPLETION_NOTIFICATION), flags);
+                    if (oldFlags == flags) break;
+                    flags = oldFlags;
+                }
+            }
+        }
+
+        /// <summary>
+        /// Calls the debugger notification method if the right bit is set and if
+        /// the task itself allows for the notification to proceed.
+        /// </summary>
+        /// <returns>true if the debugger was notified; otherwise, false.</returns>
+        internal bool NotifyDebuggerOfWaitCompletionIfNecessary()
+        {
+            // Notify the debugger if of any of the tasks we've waited on requires notification
+            if (IsWaitNotificationEnabled && ShouldNotifyDebuggerOfWaitCompletion)
+            {
+                NotifyDebuggerOfWaitCompletion();
+                return true;
+            }
+            return false;
+        }
+
+        /// <summary>Returns true if any of the supplied tasks require wait notification.</summary>
+        /// <param name="tasks">The tasks to check.</param>
+        /// <returns>true if any of the tasks require notification; otherwise, false.</returns>
+        internal static bool AnyTaskRequiresNotifyDebuggerOfWaitCompletion(Task[] tasks)
+        {
+            Debug.Assert(tasks != null, "Expected non-null array of tasks");
+            foreach (var task in tasks)
+            {
+                if (task != null &&
+                    task.IsWaitNotificationEnabled &&
+                    task.ShouldNotifyDebuggerOfWaitCompletion) // potential recursion
+                {
+                    return true;
+                }
+            }
+            return false;
+        }
+
+        /// <summary>Gets whether either the end await bit is set or (not xor) the task has not completed successfully.</summary>
+        /// <returns>(DebuggerBitSet || !RanToCompletion)</returns>
+        internal bool IsWaitNotificationEnabledOrNotRanToCompletion
+        {
+            [MethodImpl(MethodImplOptions.AggressiveInlining)]
+            get
+            {
+                return (m_stateFlags & (Task.TASK_STATE_WAIT_COMPLETION_NOTIFICATION | Task.TASK_STATE_RAN_TO_COMPLETION))
+                        != Task.TASK_STATE_RAN_TO_COMPLETION;
+            }
+        }
+
+        /// <summary>
+        /// Determines whether we should inform the debugger that we're ending a join with a task.  
+        /// This should only be called if the debugger notification bit is set, as it is has some cost,
+        /// namely it is a virtual call (however calling it if the bit is not set is not functionally 
+        /// harmful).  Derived implementations may choose to only conditionally call down to this base 
+        /// implementation.
+        /// </summary>
+        internal virtual bool ShouldNotifyDebuggerOfWaitCompletion // ideally would be familyAndAssembly, but that can't be done in C#
+        {
+            get
+            {
+                // It's theoretically possible but extremely rare that this assert could fire because the 
+                // bit was unset between the time that it was checked and this method was called.
+                // It's so remote a chance that it's worth having the assert to protect against misuse.
+                bool isWaitNotificationEnabled = IsWaitNotificationEnabled;
+                Debug.Assert(isWaitNotificationEnabled, "Should only be called if the wait completion bit is set.");
+                return isWaitNotificationEnabled;
+            }
+        }
+
+        /// <summary>Gets whether the task's debugger notification for wait completion bit is set.</summary>
+        /// <returns>true if the bit is set; false if it's not set.</returns>
+        internal bool IsWaitNotificationEnabled // internal only to enable unit tests; would otherwise be private
+        {
+            get { return (m_stateFlags & TASK_STATE_WAIT_COMPLETION_NOTIFICATION) != 0; }
+        }
+
+        /// <summary>Placeholder method used as a breakpoint target by the debugger.  Must not be inlined or optimized.</summary>
+        /// <remarks>All joins with a task should end up calling this if their debugger notification bit is set.</remarks>
+        [MethodImpl(MethodImplOptions.NoOptimization | MethodImplOptions.NoInlining)]
+        private void NotifyDebuggerOfWaitCompletion()
+        {
+            // It's theoretically possible but extremely rare that this assert could fire because the 
+            // bit was unset between the time that it was checked and this method was called.
+            // It's so remote a chance that it's worth having the assert to protect against misuse.
+            Debug.Assert(IsWaitNotificationEnabled, "Should only be called if the wait completion bit is set.");
+
+            // Now that we're notifying the debugger, clear the bit.  The debugger should do this anyway,
+            // but this adds a bit of protection in case it fails to, and given that the debugger is involved, 
+            // the overhead here for the interlocked is negligable.  We do still rely on the debugger
+            // to clear bits, as this doesn't recursively clear bits in the case of, for example, WhenAny.
+            SetNotificationForWaitCompletion(enabled: false);
+        }
+
+
+        // Atomically mark a Task as started while making sure that it is not canceled.
+        internal bool MarkStarted()
+        {
+            return AtomicStateUpdate(TASK_STATE_STARTED, TASK_STATE_CANCELED | TASK_STATE_STARTED);
+        }
+
+        /// <summary>
+        /// Internal function that will be called by a new child task to add itself to 
+        /// the children list of the parent (this).
+        /// 
+        /// Since a child task can only be created from the thread executing the action delegate
+        /// of this task, reentrancy is neither required nor supported. This should not be called from
+        /// anywhere other than the task construction/initialization codepaths.
+        /// </summary>
+        internal void AddNewChild()
+        {
+            Debug.Assert(Task.InternalCurrent == this, "Task.AddNewChild(): Called from an external context");
+
+            var props = EnsureContingentPropertiesInitialized();
+
+            if (props.m_completionCountdown == 1)
+            {
+                // A count of 1 indicates so far there was only the parent, and this is the first child task
+                // Single kid => no fuss about who else is accessing the count. Let's save ourselves 100 cycles
+                props.m_completionCountdown++;
+            }
+            else
+            {
+                // otherwise do it safely
+                Interlocked.Increment(ref props.m_completionCountdown);
+            }
+        }
+
+        // This is called in the case where a new child is added, but then encounters a CancellationToken-related exception.
+        // We need to subtract that child from m_completionCountdown, or the parent will never complete.
+        internal void DisregardChild()
+        {
+            Debug.Assert(Task.InternalCurrent == this, "Task.DisregardChild(): Called from an external context");
+
+            var props = EnsureContingentPropertiesInitialized();
+            Debug.Assert(props.m_completionCountdown >= 2, "Task.DisregardChild(): Expected parent count to be >= 2");
+            Interlocked.Decrement(ref props.m_completionCountdown);
+        }
+
+        /// <summary>
+        /// Starts the <see cref="Task"/>, scheduling it for execution to the current <see
+        /// cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see>.
+        /// </summary>
+        /// <remarks>
+        /// A task may only be started and run only once.  Any attempts to schedule a task a second time
+        /// will result in an exception.
+        /// </remarks>
+        /// <exception cref="InvalidOperationException">
+        /// The <see cref="Task"/> is not in a valid state to be started. It may have already been started,
+        /// executed, or canceled, or it may have been created in a manner that doesn't support direct
+        /// scheduling.
+        /// </exception>
+        public void Start()
+        {
+            Start(TaskScheduler.Current);
+        }
+
+        /// <summary>
+        /// Starts the <see cref="Task"/>, scheduling it for execution to the specified <see
+        /// cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see>.
+        /// </summary>
+        /// <remarks>
+        /// A task may only be started and run only once. Any attempts to schedule a task a second time will
+        /// result in an exception.
+        /// </remarks>
+        /// <param name="scheduler">
+        /// The <see cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see> with which to associate
+        /// and execute this task.
+        /// </param>
+        /// <exception cref="ArgumentNullException">
+        /// The <paramref name="scheduler"/> argument is null.
+        /// </exception>
+        /// <exception cref="InvalidOperationException">
+        /// The <see cref="Task"/> is not in a valid state to be started. It may have already been started,
+        /// executed, or canceled, or it may have been created in a manner that doesn't support direct
+        /// scheduling.
+        /// </exception>
+        public void Start(TaskScheduler scheduler)
+        {
+            // Read the volatile m_stateFlags field once and cache it for subsequent operations
+            int flags = m_stateFlags;
+
+            // Need to check this before (m_action == null) because completed tasks will
+            // set m_action to null.  We would want to know if this is the reason that m_action == null.
+            if (IsCompletedMethod(flags))
+            {
+                ThrowHelper.ThrowInvalidOperationException(ExceptionResource.Task_Start_TaskCompleted);
+            }
+
+            if (scheduler == null)
+            {
+                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler);
+            }
+
+            var options = OptionsMethod(flags);
+            if ((options & (TaskCreationOptions)InternalTaskOptions.PromiseTask) != 0)
+            {
+                ThrowHelper.ThrowInvalidOperationException(ExceptionResource.Task_Start_Promise);
+            }
+            if ((options & (TaskCreationOptions)InternalTaskOptions.ContinuationTask) != 0)
+            {
+                ThrowHelper.ThrowInvalidOperationException(ExceptionResource.Task_Start_ContinuationTask);
+            }
+
+            // Make sure that Task only gets started once.  Or else throw an exception.
+            if (Interlocked.CompareExchange(ref m_taskScheduler, scheduler, null) != null)
+            {
+                ThrowHelper.ThrowInvalidOperationException(ExceptionResource.Task_Start_AlreadyStarted);
+            }
+
+            ScheduleAndStart(true);
+        }
+
+        /// <summary>
+        /// Runs the <see cref="Task"/> synchronously on the current <see
+        /// cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see>.
+        /// </summary>
+        /// <remarks>
+        /// <para>
+        /// A task may only be started and run only once. Any attempts to schedule a task a second time will
+        /// result in an exception.
+        /// </para>
+        /// <para>
+        /// Tasks executed with <see cref="RunSynchronously()"/> will be associated with the current <see
+        /// cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see>.
+        /// </para>
+        /// <para>
+        /// If the target scheduler does not support running this Task on the current thread, the Task will
+        /// be scheduled for execution on the scheduler, and the current thread will block until the
+        /// Task has completed execution.
+        /// </para>
+        /// </remarks>
+        /// <exception cref="InvalidOperationException">
+        /// The <see cref="Task"/> is not in a valid state to be started. It may have already been started,
+        /// executed, or canceled, or it may have been created in a manner that doesn't support direct
+        /// scheduling.
+        /// </exception>
+        public void RunSynchronously()
+        {
+            InternalRunSynchronously(TaskScheduler.Current, waitForCompletion: true);
+        }
+
+        /// <summary>
+        /// Runs the <see cref="Task"/> synchronously on the <see
+        /// cref="System.Threading.Tasks.TaskScheduler">scheduler</see> provided.
+        /// </summary>
+        /// <remarks>
+        /// <para>
+        /// A task may only be started and run only once. Any attempts to schedule a task a second time will
+        /// result in an exception.
+        /// </para>
+        /// <para>
+        /// If the target scheduler does not support running this Task on the current thread, the Task will
+        /// be scheduled for execution on the scheduler, and the current thread will block until the
+        /// Task has completed execution.
+        /// </para>
+        /// </remarks>
+        /// <exception cref="InvalidOperationException">
+        /// The <see cref="Task"/> is not in a valid state to be started. It may have already been started,
+        /// executed, or canceled, or it may have been created in a manner that doesn't support direct
+        /// scheduling.
+        /// </exception>
+        /// <exception cref="ArgumentNullException">The <paramref name="scheduler"/> parameter
+        /// is null.</exception>
+        /// <param name="scheduler">The scheduler on which to attempt to run this task inline.</param>
+        public void RunSynchronously(TaskScheduler scheduler)
+        {
+            if (scheduler == null)
+            {
+                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler);
+            }
+
+            InternalRunSynchronously(scheduler, waitForCompletion: true);
+        }
+
+        //
+        // Internal version of RunSynchronously that allows not waiting for completion.
+        // 
+        internal void InternalRunSynchronously(TaskScheduler scheduler, bool waitForCompletion)
+        {
+            Debug.Assert(scheduler != null, "Task.InternalRunSynchronously(): null TaskScheduler");
+
+            // Read the volatile m_stateFlags field once and cache it for subsequent operations
+            int flags = m_stateFlags;
+
+            // Can't call this method on a continuation task
+            var options = OptionsMethod(flags);
+            if ((options & (TaskCreationOptions)InternalTaskOptions.ContinuationTask) != 0)
+            {
+                ThrowHelper.ThrowInvalidOperationException(ExceptionResource.Task_RunSynchronously_Continuation);
+            }
+
+            // Can't call this method on a promise-style task
+            if ((options & (TaskCreationOptions)InternalTaskOptions.PromiseTask) != 0)
+            {
+                ThrowHelper.ThrowInvalidOperationException(ExceptionResource.Task_RunSynchronously_Promise);
+            }
+
+            // Can't call this method on a task that has already completed
+            if (IsCompletedMethod(flags))
+            {
+                ThrowHelper.ThrowInvalidOperationException(ExceptionResource.Task_RunSynchronously_TaskCompleted);
+            }
+
+            // Make sure that Task only gets started once.  Or else throw an exception.
+            if (Interlocked.CompareExchange(ref m_taskScheduler, scheduler, null) != null)
+            {
+                ThrowHelper.ThrowInvalidOperationException(ExceptionResource.Task_RunSynchronously_AlreadyStarted);
+            }
+
+            // execute only if we successfully cancel when concurrent cancel attempts are made.
+            // otherwise throw an exception, because we've been canceled.
+            if (MarkStarted())
+            {
+                bool taskQueued = false;
+                try
+                {
+                    // We wrap TryRunInline() in a try/catch block and move an excepted task to Faulted here,
+                    // but not in Wait()/WaitAll()/FastWaitAll().  Here, we know for sure that the
+                    // task will not be subsequently scheduled (assuming that the scheduler adheres
+                    // to the guideline that an exception implies that no state change took place),
+                    // so it is safe to catch the exception and move the task to a final state.  The
+                    // same cannot be said for Wait()/WaitAll()/FastWaitAll().
+                    if (!scheduler.TryRunInline(this, false))
+                    {
+                        scheduler.InternalQueueTask(this);
+                        taskQueued = true; // only mark this after successfully queuing the task.
+                    }
+
+                    // A successful TryRunInline doesn't guarantee completion, as there may be unfinished children.
+                    // Also if we queued the task above, the task may not be done yet.
+                    if (waitForCompletion && !IsCompleted)
+                    {
+                        SpinThenBlockingWait(Timeout.Infinite, default);
+                    }
+                }
+                catch (Exception e)
+                {
+                    // we 1) either received an unexpected exception originating from a custom scheduler, which needs to be wrapped in a TSE and thrown
+                    //    2) or a a ThreadAbortException, which we need to skip here, because it would already have been handled in Task.Execute
+                    if (!taskQueued && !(e is ThreadAbortException))
+                    {
+                        // We had a problem with TryRunInline() or QueueTask().  
+                        // Record the exception, marking ourselves as Completed/Faulted.
+                        TaskSchedulerException tse = new TaskSchedulerException(e);
+                        AddException(tse);
+                        Finish(false);
+
+                        // Mark ourselves as "handled" to avoid crashing the finalizer thread if the caller neglects to
+                        // call Wait() on this task.
+                        // m_contingentProperties.m_exceptionsHolder *should* already exist after AddException()
+                        Debug.Assert(
+                            (m_contingentProperties != null) &&
+                            (m_contingentProperties.m_exceptionsHolder != null) &&
+                            (m_contingentProperties.m_exceptionsHolder.ContainsFaultList),
+                            "Task.InternalRunSynchronously(): Expected m_contingentProperties.m_exceptionsHolder to exist " +
+                            "and to have faults recorded.");
+                        m_contingentProperties.m_exceptionsHolder.MarkAsHandled(false);
+
+                        // And re-throw.
+                        throw tse;
+                    }
+                    // We had a problem with waiting or this is a thread abort.  Just re-throw.
+                    else throw;
+                }
+            }
+            else
+            {
+                Debug.Assert((m_stateFlags & TASK_STATE_CANCELED) != 0, "Task.RunSynchronously: expected TASK_STATE_CANCELED to be set");
+                // Can't call this method on canceled task.
+                ThrowHelper.ThrowInvalidOperationException(ExceptionResource.Task_RunSynchronously_TaskCompleted);
+            }
+        }
+
+
+        ////
+        //// Helper methods for Factory StartNew methods.
+        ////
+
+
+        // Implicitly converts action to object and handles the meat of the StartNew() logic.
+        internal static Task InternalStartNew(
+            Task creatingTask, Delegate action, object state, CancellationToken cancellationToken, TaskScheduler scheduler,
+            TaskCreationOptions options, InternalTaskOptions internalOptions)
+        {
+            // Validate arguments.
+            if (scheduler == null)
+            {
+                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler);
+            }
+
+            // Create and schedule the task. This throws an InvalidOperationException if already shut down.
+            // Here we add the InternalTaskOptions.QueuedByRuntime to the internalOptions, so that TaskConstructorCore can skip the cancellation token registration
+            Task t = new Task(action, state, creatingTask, cancellationToken, options, internalOptions | InternalTaskOptions.QueuedByRuntime, scheduler);
+
+            t.ScheduleAndStart(false);
+            return t;
+        }
+
+
+        /// <summary>
+        /// Gets a unique ID for this <see cref="Task">Task</see> instance.
+        /// </summary>
+        /// <remarks>
+        /// Task IDs are assigned on-demand and do not necessarily represent the order in the which Task
+        /// instances were created.
+        /// </remarks>
+        public int Id
+        {
+            get
+            {
+                if (m_taskId == 0)
+                {
+                    int newId = 0;
+                    // We need to repeat if Interlocked.Increment wraps around and returns 0.
+                    // Otherwise next time this task's Id is queried it will get a new value
+                    do
+                    {
+                        newId = Interlocked.Increment(ref s_taskIdCounter);
+                    }
+                    while (newId == 0);
+
+                    Interlocked.CompareExchange(ref m_taskId, newId, 0);
+                }
+
+                return m_taskId;
+            }
+        }
+
+        /// <summary>
+        /// Returns the unique ID of the currently executing <see cref="Task">Task</see>.
+        /// </summary>
+        public static int? CurrentId
+        {
+            get
+            {
+                Task currentTask = InternalCurrent;
+                if (currentTask != null)
+                    return currentTask.Id;
+                else
+                    return null;
+            }
+        }
+
+        /// <summary>
+        /// Gets the <see cref="Task">Task</see> instance currently executing, or
+        /// null if none exists.
+        /// </summary>
+        internal static Task InternalCurrent
+        {
+            get { return t_currentTask; }
+        }
+
+        /// <summary>
+        /// Gets the Task instance currently executing if the specified creation options
+        /// contain AttachedToParent.
+        /// </summary>
+        /// <param name="creationOptions">The options to check.</param>
+        /// <returns>The current task if there is one and if AttachToParent is in the options; otherwise, null.</returns>
+        internal static Task InternalCurrentIfAttached(TaskCreationOptions creationOptions)
+        {
+            return (creationOptions & TaskCreationOptions.AttachedToParent) != 0 ? InternalCurrent : null;
+        }
+
+        /// <summary>
+        /// Gets the StackGuard object assigned to the current thread.
+        /// </summary>
+        internal static StackGuard CurrentStackGuard
+        {
+            get
+            {
+                StackGuard sg = t_stackGuard;
+                if (sg == null)
+                {
+                    t_stackGuard = sg = new StackGuard();
+                }
+                return sg;
+            }
+        }
+
+
+        /// <summary>
+        /// Gets the <see cref="T:System.AggregateException">Exception</see> that caused the <see
+        /// cref="Task">Task</see> to end prematurely. If the <see
+        /// cref="Task">Task</see> completed successfully or has not yet thrown any
+        /// exceptions, this will return null.
+        /// </summary>
+        /// <remarks>
+        /// Tasks that throw unhandled exceptions store the resulting exception and propagate it wrapped in a
+        /// <see cref="System.AggregateException"/> in calls to <see cref="Wait()">Wait</see>
+        /// or in accesses to the <see cref="Exception"/> property.  Any exceptions not observed by the time
+        /// the Task instance is garbage collected will be propagated on the finalizer thread.
+        /// </remarks>
+        public AggregateException Exception
+        {
+            get
+            {
+                AggregateException e = null;
+
+                // If you're faulted, retrieve the exception(s)
+                if (IsFaulted) e = GetExceptions(false);
+
+                // Only return an exception in faulted state (skip manufactured exceptions)
+                // A "benevolent" race condition makes it possible to return null when IsFaulted is
+                // true (i.e., if IsFaulted is set just after the check to IsFaulted above).
+                Debug.Assert((e == null) || IsFaulted, "Task.Exception_get(): returning non-null value when not Faulted");
+
+                return e;
+            }
+        }
+
+        /// <summary>
+        /// Gets the <see cref="T:System.Threading.Tasks.TaskStatus">TaskStatus</see> of this Task. 
+        /// </summary>
+        public TaskStatus Status
+        {
+            get
+            {
+                TaskStatus rval;
+
+                // get a cached copy of the state flags.  This should help us
+                // to get a consistent view of the flags if they are changing during the
+                // execution of this method.
+                int sf = m_stateFlags;
+
+                if ((sf & TASK_STATE_FAULTED) != 0) rval = TaskStatus.Faulted;
+                else if ((sf & TASK_STATE_CANCELED) != 0) rval = TaskStatus.Canceled;
+                else if ((sf & TASK_STATE_RAN_TO_COMPLETION) != 0) rval = TaskStatus.RanToCompletion;
+                else if ((sf & TASK_STATE_WAITING_ON_CHILDREN) != 0) rval = TaskStatus.WaitingForChildrenToComplete;
+                else if ((sf & TASK_STATE_DELEGATE_INVOKED) != 0) rval = TaskStatus.Running;
+                else if ((sf & TASK_STATE_STARTED) != 0) rval = TaskStatus.WaitingToRun;
+                else if ((sf & TASK_STATE_WAITINGFORACTIVATION) != 0) rval = TaskStatus.WaitingForActivation;
+                else rval = TaskStatus.Created;
+
+                return rval;
+            }
+        }
+
+        /// <summary>
+        /// Gets whether this <see cref="Task">Task</see> instance has completed
+        /// execution due to being canceled.
+        /// </summary>
+        /// <remarks>
+        /// A <see cref="Task">Task</see> will complete in Canceled state either if its <see cref="CancellationToken">CancellationToken</see> 
+        /// was marked for cancellation before the task started executing, or if the task acknowledged the cancellation request on 
+        /// its already signaled CancellationToken by throwing an 
+        /// <see cref="System.OperationCanceledException">OperationCanceledException</see> that bears the same 
+        /// <see cref="System.Threading.CancellationToken">CancellationToken</see>.
+        /// </remarks>
+        public bool IsCanceled
+        {
+            get
+            {
+                // Return true if canceled bit is set and faulted bit is not set
+                return (m_stateFlags & (TASK_STATE_CANCELED | TASK_STATE_FAULTED)) == TASK_STATE_CANCELED;
+            }
+        }
+
+        /// <summary>
+        /// Returns true if this task has a cancellation token and it was signaled.
+        /// To be used internally in execute entry codepaths.
+        /// </summary>
+        internal bool IsCancellationRequested
+        {
+            get
+            {
+                // check both the internal cancellation request flag and the CancellationToken attached to this task
+                var props = Volatile.Read(ref m_contingentProperties);
+                return props != null &&
+                    (props.m_internalCancellationRequested == CANCELLATION_REQUESTED ||
+                     props.m_cancellationToken.IsCancellationRequested);
+            }
+        }
+
+        /// <summary>
+        /// Ensures that the contingent properties field has been initialized.
+        /// ASSUMES THAT m_stateFlags IS ALREADY SET!
+        /// </summary>
+        /// <returns>The initialized contingent properties object.</returns>
+        internal ContingentProperties EnsureContingentPropertiesInitialized()
+        {
+            return LazyInitializer.EnsureInitialized(ref m_contingentProperties, () => new ContingentProperties());
+        }
+
+        /// <summary>
+        /// Without synchronization, ensures that the contingent properties field has been initialized.
+        /// ASSUMES THAT m_stateFlags IS ALREADY SET!
+        /// </summary>
+        /// <returns>The initialized contingent properties object.</returns>
+        internal ContingentProperties EnsureContingentPropertiesInitializedUnsafe()
+        {
+            return m_contingentProperties ?? (m_contingentProperties = new ContingentProperties());
+        }
+
+        /// <summary>
+        /// This internal property provides access to the CancellationToken that was set on the task 
+        /// when it was constructed.
+        /// </summary>
+        internal CancellationToken CancellationToken
+        {
+            get
+            {
+                var props = Volatile.Read(ref m_contingentProperties);
+                return (props == null) ? default : props.m_cancellationToken;
+            }
+        }
+
+        /// <summary>
+        /// Gets whether this <see cref="Task"/> threw an OperationCanceledException while its CancellationToken was signaled.
+        /// </summary>
+        internal bool IsCancellationAcknowledged
+        {
+            get { return (m_stateFlags & TASK_STATE_CANCELLATIONACKNOWLEDGED) != 0; }
+        }
+
+
+        /// <summary>
+        /// Gets whether this <see cref="Task">Task</see> has completed.
+        /// </summary>
+        /// <remarks>
+        /// <see cref="IsCompleted"/> will return true when the Task is in one of the three
+        /// final states: <see cref="System.Threading.Tasks.TaskStatus.RanToCompletion">RanToCompletion</see>,
+        /// <see cref="System.Threading.Tasks.TaskStatus.Faulted">Faulted</see>, or
+        /// <see cref="System.Threading.Tasks.TaskStatus.Canceled">Canceled</see>.
+        /// </remarks>
+        public bool IsCompleted
+        {
+            get
+            {
+                int stateFlags = m_stateFlags; // enable inlining of IsCompletedMethod by "cast"ing away the volatility
+                return IsCompletedMethod(stateFlags);
+            }
+        }
+
+        // Similar to IsCompleted property, but allows for the use of a cached flags value
+        // rather than reading the volatile m_stateFlags field.
+        private static bool IsCompletedMethod(int flags)
+        {
+            return (flags & TASK_STATE_COMPLETED_MASK) != 0;
+        }
+
+        public bool IsCompletedSuccessfully
+        {
+            get { return (m_stateFlags & TASK_STATE_COMPLETED_MASK) == TASK_STATE_RAN_TO_COMPLETION; }
+        }
+
+        /// <summary>
+        /// Gets the <see cref="T:System.Threading.Tasks.TaskCreationOptions">TaskCreationOptions</see> used
+        /// to create this task.
+        /// </summary>
+        public TaskCreationOptions CreationOptions
+        {
+            get { return Options & (TaskCreationOptions)(~InternalTaskOptions.InternalOptionsMask); }
+        }
+
+        /// <summary>
+        /// Gets a <see cref="T:System.Threading.WaitHandle"/> that can be used to wait for the task to
+        /// complete.
+        /// </summary>
+        /// <remarks>
+        /// Using the wait functionality provided by <see cref="Wait()"/>
+        /// should be preferred over using <see cref="IAsyncResult.AsyncWaitHandle"/> for similar
+        /// functionality.
+        /// </remarks>
+        /// <exception cref="T:System.ObjectDisposedException">
+        /// The <see cref="Task"/> has been disposed.
+        /// </exception>
+        WaitHandle IAsyncResult.AsyncWaitHandle
+        {
+            // Although a slim event is used internally to avoid kernel resource allocation, this function
+            // forces allocation of a true WaitHandle when called.
+            get
+            {
+                bool isDisposed = (m_stateFlags & TASK_STATE_DISPOSED) != 0;
+                if (isDisposed)
+                {
+                    ThrowHelper.ThrowObjectDisposedException(ExceptionResource.Task_ThrowIfDisposed);
+                }
+                return CompletedEvent.WaitHandle;
+            }
+        }
+
+        /// <summary>
+        /// Gets the state object supplied when the <see cref="Task">Task</see> was created,
+        /// or null if none was supplied.
+        /// </summary>
+        public object AsyncState
+        {
+            get { return m_stateObject; }
+        }
+
+        /// <summary>
+        /// Gets an indication of whether the asynchronous operation completed synchronously.
+        /// </summary>
+        /// <value>true if the asynchronous operation completed synchronously; otherwise, false.</value>
+        bool IAsyncResult.CompletedSynchronously
+        {
+            get
+            {
+                return false;
+            }
+        }
+
+        /// <summary>
+        /// Provides access to the TaskScheduler responsible for executing this Task.
+        /// </summary>
+        internal TaskScheduler ExecutingTaskScheduler
+        {
+            get { return m_taskScheduler; }
+        }
+
+        /// <summary>
+        /// Provides access to factory methods for creating <see cref="Task"/> and <see cref="Task{TResult}"/> instances.
+        /// </summary>
+        /// <remarks>
+        /// The factory returned from <see cref="Factory"/> is a default instance
+        /// of <see cref="System.Threading.Tasks.TaskFactory"/>, as would result from using
+        /// the default constructor on TaskFactory.
+        /// </remarks>
+        public static TaskFactory Factory { get; } = new TaskFactory();
+
+        /// <summary>Gets a task that's already been completed successfully.</summary>
+        public static Task CompletedTask { get; } = new Task(false, (TaskCreationOptions)InternalTaskOptions.DoNotDispose, default);
+
+        /// <summary>
+        /// Provides an event that can be used to wait for completion.
+        /// Only called by IAsyncResult.AsyncWaitHandle, which means that we really do need to instantiate a completion event.
+        /// </summary>
+        internal ManualResetEventSlim CompletedEvent
+        {
+            get
+            {
+                var contingentProps = EnsureContingentPropertiesInitialized();
+                if (contingentProps.m_completionEvent == null)
+                {
+                    bool wasCompleted = IsCompleted;
+                    ManualResetEventSlim newMre = new ManualResetEventSlim(wasCompleted);
+                    if (Interlocked.CompareExchange(ref contingentProps.m_completionEvent, newMre, null) != null)
+                    {
+                        // Someone else already set the value, so we will just close the event right away.
+                        newMre.Dispose();
+                    }
+                    else if (!wasCompleted && IsCompleted)
+                    {
+                        // We published the event as unset, but the task has subsequently completed.
+                        // Set the event's state properly so that callers don't deadlock.
+                        newMre.Set();
+                    }
+                }
+
+                return contingentProps.m_completionEvent;
+            }
+        }
+
+
+        /// <summary>
+        /// The property formerly known as IsFaulted.
+        /// </summary>
+        internal bool ExceptionRecorded
+        {
+            get
+            {
+                var props = Volatile.Read(ref m_contingentProperties);
+                return (props != null) && (props.m_exceptionsHolder != null) && (props.m_exceptionsHolder.ContainsFaultList);
+            }
+        }
+
+        /// <summary>
+        /// Gets whether the <see cref="Task"/> completed due to an unhandled exception.
+        /// </summary>
+        /// <remarks>
+        /// If <see cref="IsFaulted"/> is true, the Task's <see cref="Status"/> will be equal to
+        /// <see cref="System.Threading.Tasks.TaskStatus.Faulted">TaskStatus.Faulted</see>, and its
+        /// <see cref="Exception"/> property will be non-null.
+        /// </remarks>
+        public bool IsFaulted
+        {
+            get
+            {
+                // Faulted is "king" -- if that bit is present (regardless of other bits), we are faulted.
+                return ((m_stateFlags & TASK_STATE_FAULTED) != 0);
+            }
+        }
+
+        /// <summary>
+        /// The captured execution context for the current task to run inside
+        /// If the TASK_STATE_EXECUTIONCONTEXT_IS_NULL flag is set, this means ExecutionContext.Capture returned null, otherwise
+        /// If the captured context is the default, nothing is saved, otherwise the m_contingentProperties inflates to save the context
+        /// </summary>
+        internal ExecutionContext CapturedContext
+        {
+            get
+            {
+                if ((m_stateFlags & TASK_STATE_EXECUTIONCONTEXT_IS_NULL) == TASK_STATE_EXECUTIONCONTEXT_IS_NULL)
+                {
+                    return null;
+                }
+                else
+                {
+                    return m_contingentProperties?.m_capturedContext ?? ExecutionContext.Default;
+                }
+            }
+            set
+            {
+                // There is no need to atomically set this bit because this set() method is only called during construction, and therefore there should be no contending accesses to m_stateFlags
+                if (value == null)
+                {
+                    m_stateFlags |= TASK_STATE_EXECUTIONCONTEXT_IS_NULL;
+                }
+                else if (value != ExecutionContext.Default) // not the default context, then inflate the contingent properties and set it
+                {
+                    EnsureContingentPropertiesInitializedUnsafe().m_capturedContext = value;
+                }
+                //else do nothing, this is the default context
+            }
+        }
+
+        /////////////
+        // methods
+
+
+        /// <summary>
+        /// Disposes the <see cref="Task"/>, releasing all of its unmanaged resources.
+        /// </summary>
+        /// <remarks>
+        /// Unlike most of the members of <see cref="Task"/>, this method is not thread-safe.
+        /// Also, <see cref="Dispose()"/> may only be called on a <see cref="Task"/> that is in one of
+        /// the final states: <see cref="System.Threading.Tasks.TaskStatus.RanToCompletion">RanToCompletion</see>,
+        /// <see cref="System.Threading.Tasks.TaskStatus.Faulted">Faulted</see>, or
+        /// <see cref="System.Threading.Tasks.TaskStatus.Canceled">Canceled</see>.
+        /// </remarks>
+        /// <exception cref="T:System.InvalidOperationException">
+        /// The exception that is thrown if the <see cref="Task"/> is not in
+        /// one of the final states: <see cref="System.Threading.Tasks.TaskStatus.RanToCompletion">RanToCompletion</see>,
+        /// <see cref="System.Threading.Tasks.TaskStatus.Faulted">Faulted</see>, or
+        /// <see cref="System.Threading.Tasks.TaskStatus.Canceled">Canceled</see>.
+        /// </exception>
+        public void Dispose()
+        {
+            Dispose(true);
+            GC.SuppressFinalize(this);
+        }
+
+        /// <summary>
+        /// Disposes the <see cref="Task"/>, releasing all of its unmanaged resources.
+        /// </summary>
+        /// <param name="disposing">
+        /// A Boolean value that indicates whether this method is being called due to a call to <see
+        /// cref="Dispose()"/>.
+        /// </param>
+        /// <remarks>
+        /// Unlike most of the members of <see cref="Task"/>, this method is not thread-safe.
+        /// </remarks>
+        protected virtual void Dispose(bool disposing)
+        {
+            if (disposing)
+            {
+                // Dispose is a nop if this task was created with the DoNotDispose internal option.
+                // This is done before the completed check, because if we're not touching any 
+                // state on the task, it's ok for it to happen before completion.
+                if ((Options & (TaskCreationOptions)InternalTaskOptions.DoNotDispose) != 0)
+                {
+                    return;
+                }
+
+                // Task must be completed to dispose
+                if (!IsCompleted)
+                {
+                    ThrowHelper.ThrowInvalidOperationException(ExceptionResource.Task_Dispose_NotCompleted);
+                }
+
+                // Dispose of the underlying completion event if it exists
+                var cp = Volatile.Read(ref m_contingentProperties);
+                if (cp != null)
+                {
+                    // Make a copy to protect against racing Disposes.
+                    // If we wanted to make this a bit safer, we could use an interlocked here,
+                    // but we state that Dispose is not thread safe.
+                    var ev = cp.m_completionEvent;
+                    if (ev != null)
+                    {
+                        // Null out the completion event in contingent props; we'll use our copy from here on out
+                        cp.m_completionEvent = null;
+
+                        // In the unlikely event that our completion event is inflated but not yet signaled,
+                        // go ahead and signal the event.  If you dispose of an unsignaled MRES, then any waiters
+                        // will deadlock; an ensuing Set() will not wake them up.  In the event of an AppDomainUnload,
+                        // there is no guarantee that anyone else is going to signal the event, and it does no harm to 
+                        // call Set() twice on m_completionEvent.
+                        if (!ev.IsSet) ev.Set();
+
+                        // Finally, dispose of the event
+                        ev.Dispose();
+                    }
+                }
+            }
+
+            // We OR the flags to indicate the object has been disposed. The task
+            // has already completed at this point, and the only conceivable race condition would
+            // be with the unsetting of the TASK_STATE_WAIT_COMPLETION_NOTIFICATION flag, which
+            // is extremely unlikely and also benign.  (Worst case: we hit a breakpoint
+            // twice instead of once in the debugger.  Weird, but not lethal.)
+            m_stateFlags |= TASK_STATE_DISPOSED;
+        }
+
+        /////////////
+        // internal helpers
+
+
+        /// <summary>
+        /// Schedules the task for execution.
+        /// </summary>
+        /// <param name="needsProtection">If true, TASK_STATE_STARTED bit is turned on in
+        /// an atomic fashion, making sure that TASK_STATE_CANCELED does not get set
+        /// underneath us.  If false, TASK_STATE_STARTED bit is OR-ed right in.  This
+        /// allows us to streamline things a bit for StartNew(), where competing cancellations
+        /// are not a problem.</param>
+        internal void ScheduleAndStart(bool needsProtection)
+        {
+            Debug.Assert(m_taskScheduler != null, "expected a task scheduler to have been selected");
+            Debug.Assert((m_stateFlags & TASK_STATE_STARTED) == 0, "task has already started");
+
+            // Set the TASK_STATE_STARTED bit
+            if (needsProtection)
+            {
+                if (!MarkStarted())
+                {
+                    // A cancel has snuck in before we could get started.  Quietly exit.
+                    return;
+                }
+            }
+            else
+            {
+                m_stateFlags |= TASK_STATE_STARTED;
+            }
+
+            DebuggerSupport.AddToActiveTasks(this);
+            if (DebuggerSupport.LoggingOn && (Options & (TaskCreationOptions)InternalTaskOptions.ContinuationTask) == 0)
+            {
+                //For all other task than TaskContinuations we want to log. TaskContinuations log in their constructor
+                DebuggerSupport.TraceOperationCreation(CausalityTraceLevel.Required, this, "Task: " + m_action, 0);
+            }
+
+
+            try
+            {
+                // Queue to the indicated scheduler.
+                m_taskScheduler.InternalQueueTask(this);
+            }
+            //catch (ThreadAbortException tae)
+            //{
+            //    AddException(tae);
+            //    FinishThreadAbortedTask(true, false);
+            //}
+            catch (Exception e)
+            {
+                // The scheduler had a problem queueing this task.  Record the exception, leaving this task in
+                // a Faulted state.
+                TaskSchedulerException tse = new TaskSchedulerException(e);
+                AddException(tse);
+                Finish(false);
+
+                // Now we need to mark ourselves as "handled" to avoid crashing the finalizer thread if we are called from StartNew(),
+                // because the exception is either propagated outside directly, or added to an enclosing parent. However we won't do this for
+                // continuation tasks, because in that case we internally eat the exception and therefore we need to make sure the user does
+                // later observe it explicitly or see it on the finalizer.
+
+                if ((Options & (TaskCreationOptions)InternalTaskOptions.ContinuationTask) == 0)
+                {
+                    // m_contingentProperties.m_exceptionsHolder *should* already exist after AddException()
+                    Debug.Assert(
+                        (m_contingentProperties != null) &&
+                        (m_contingentProperties.m_exceptionsHolder != null) &&
+                        (m_contingentProperties.m_exceptionsHolder.ContainsFaultList),
+                            "Task.ScheduleAndStart(): Expected m_contingentProperties.m_exceptionsHolder to exist " +
+                            "and to have faults recorded.");
+
+                    m_contingentProperties.m_exceptionsHolder.MarkAsHandled(false);
+                }
+                // re-throw the exception wrapped as a TaskSchedulerException.
+                throw tse;
+            }
+        }
+
+        /// <summary>
+        /// Adds an exception to the list of exceptions this task has thrown.
+        /// </summary>
+        /// <param name="exceptionObject">An object representing either an Exception or a collection of Exceptions.</param>
+        internal void AddException(object exceptionObject)
+        {
+            Debug.Assert(exceptionObject != null, "Task.AddException: Expected a non-null exception object");
+            AddException(exceptionObject, representsCancellation: false);
+        }
+
+        /// <summary>
+        /// Adds an exception to the list of exceptions this task has thrown.
+        /// </summary>
+        /// <param name="exceptionObject">An object representing either an Exception or a collection of Exceptions.</param>
+        /// <param name="representsCancellation">Whether the exceptionObject is an OperationCanceledException representing cancellation.</param>
+        internal void AddException(object exceptionObject, bool representsCancellation)
+        {
+            Debug.Assert(exceptionObject != null, "Task.AddException: Expected a non-null exception object");
+
+#if DEBUG
+            var eoAsException = exceptionObject as Exception;
+            var eoAsEnumerableException = exceptionObject as IEnumerable<Exception>;
+            var eoAsEdi = exceptionObject as ExceptionDispatchInfo;
+            var eoAsEnumerableEdi = exceptionObject as IEnumerable<ExceptionDispatchInfo>;
+
+            Debug.Assert(
+                eoAsException != null || eoAsEnumerableException != null || eoAsEdi != null || eoAsEnumerableEdi != null,
+                "Task.AddException: Expected an Exception, ExceptionDispatchInfo, or an IEnumerable<> of one of those");
+
+            var eoAsOce = exceptionObject as OperationCanceledException;
+
+            Debug.Assert(
+                !representsCancellation ||
+                eoAsOce != null ||
+                (eoAsEdi != null && eoAsEdi.SourceException is OperationCanceledException),
+                "representsCancellation should be true only if an OCE was provided.");
+#endif
+
+            //
+            // WARNING: A great deal of care went into ensuring that
+            // AddException() and GetExceptions() are never called
+            // simultaneously.  See comment at start of GetExceptions().
+            //
+
+            // Lazily initialize the holder, ensuring only one thread wins.
+            var props = EnsureContingentPropertiesInitialized();
+            if (props.m_exceptionsHolder == null)
+            {
+                TaskExceptionHolder holder = new TaskExceptionHolder(this);
+                if (Interlocked.CompareExchange(ref props.m_exceptionsHolder, holder, null) != null)
+                {
+                    // If someone else already set the value, suppress finalization.
+                    holder.MarkAsHandled(false);
+                }
+            }
+
+            lock (props)
+            {
+                props.m_exceptionsHolder.Add(exceptionObject, representsCancellation);
+            }
+        }
+
+        /// <summary>
+        /// Returns a list of exceptions by aggregating the holder's contents. Or null if
+        /// no exceptions have been thrown.
+        /// </summary>
+        /// <param name="includeTaskCanceledExceptions">Whether to include a TCE if cancelled.</param>
+        /// <returns>An aggregate exception, or null if no exceptions have been caught.</returns>
+        private AggregateException GetExceptions(bool includeTaskCanceledExceptions)
+        {
+            //
+            // WARNING: The Task/Task<TResult>/TaskCompletionSource classes
+            // have all been carefully crafted to insure that GetExceptions()
+            // is never called while AddException() is being called.  There
+            // are locks taken on m_contingentProperties in several places:
+            //
+            // -- Task<TResult>.TrySetException(): The lock allows the
+            //    task to be set to Faulted state, and all exceptions to
+            //    be recorded, in one atomic action.  
+            //
+            // -- Task.Exception_get(): The lock ensures that Task<TResult>.TrySetException()
+            //    is allowed to complete its operation before Task.Exception_get()
+            //    can access GetExceptions().
+            //
+            // -- Task.ThrowIfExceptional(): The lock insures that Wait() will
+            //    not attempt to call GetExceptions() while Task<TResult>.TrySetException()
+            //    is in the process of calling AddException().
+            //
+            // For "regular" tasks, we effectively keep AddException() and GetException()
+            // from being called concurrently by the way that the state flows.  Until
+            // a Task is marked Faulted, Task.Exception_get() returns null.  And
+            // a Task is not marked Faulted until it and all of its children have
+            // completed, which means that all exceptions have been recorded.
+            //
+            // It might be a lot easier to follow all of this if we just required
+            // that all calls to GetExceptions() and AddExceptions() were made
+            // under a lock on m_contingentProperties.  But that would also
+            // increase our lock occupancy time and the frequency with which we
+            // would need to take the lock.
+            //
+            // If you add a call to GetExceptions() anywhere in the code,
+            // please continue to maintain the invariant that it can't be
+            // called when AddException() is being called.
+            //
+
+            // We'll lazily create a TCE if the task has been canceled.
+            Exception canceledException = null;
+            if (includeTaskCanceledExceptions && IsCanceled)
+            {
+                // Backcompat: 
+                // Ideally we'd just use the cached OCE from this.GetCancellationExceptionDispatchInfo()
+                // here.  However, that would result in a potentially breaking change from .NET 4, which
+                // has the code here that throws a new exception instead of the original, and the EDI
+                // may not contain a TCE, but an OCE or any OCE-derived type, which would mean we'd be
+                // propagating an exception of a different type.
+                canceledException = new TaskCanceledException(this);
+            }
+
+            if (ExceptionRecorded)
+            {
+                // There are exceptions; get the aggregate and optionally add the canceled
+                // exception to the aggregate (if applicable).
+                Debug.Assert(m_contingentProperties != null); // ExceptionRecorded ==> m_contingentProperties != null
+
+                // No need to lock around this, as other logic prevents the consumption of exceptions
+                // before they have been completely processed.
+                return m_contingentProperties.m_exceptionsHolder.CreateExceptionObject(false, canceledException);
+            }
+            else if (canceledException != null)
+            {
+                // No exceptions, but there was a cancelation. Aggregate and return it.
+                return new AggregateException(canceledException);
+            }
+
+            return null;
+        }
+
+        /// <summary>Gets the exception dispatch infos once the task has faulted.</summary>
+        internal ReadOnlyCollection<ExceptionDispatchInfo> GetExceptionDispatchInfos()
+        {
+            bool exceptionsAvailable = IsFaulted && ExceptionRecorded;
+            Debug.Assert(exceptionsAvailable, "Must only be used when the task has faulted with exceptions.");
+            return exceptionsAvailable ?
+                m_contingentProperties.m_exceptionsHolder.GetExceptionDispatchInfos() :
+                new ReadOnlyCollection<ExceptionDispatchInfo>(new ExceptionDispatchInfo[0]);
+        }
+
+        /// <summary>Gets the ExceptionDispatchInfo containing the OperationCanceledException for this task.</summary>
+        /// <returns>The ExceptionDispatchInfo.  May be null if no OCE was stored for the task.</returns>
+        internal ExceptionDispatchInfo GetCancellationExceptionDispatchInfo()
+        {
+            Debug.Assert(IsCanceled, "Must only be used when the task has canceled.");
+            return Volatile.Read(ref m_contingentProperties)?.m_exceptionsHolder?.GetCancellationExceptionDispatchInfo(); // may be null
+        }
+
+        /// <summary>
+        /// Throws an aggregate exception if the task contains exceptions. 
+        /// </summary>
+        internal void ThrowIfExceptional(bool includeTaskCanceledExceptions)
+        {
+            Debug.Assert(IsCompleted, "ThrowIfExceptional(): Expected IsCompleted == true");
+
+            Exception exception = GetExceptions(includeTaskCanceledExceptions);
+            if (exception != null)
+            {
+                UpdateExceptionObservedStatus();
+                throw exception;
+            }
+        }
+
+        /// <summary>
+        /// Checks whether this is an attached task, and whether we are being called by the parent task.
+        /// And sets the TASK_STATE_EXCEPTIONOBSERVEDBYPARENT status flag based on that.
+        /// 
+        /// This is meant to be used internally when throwing an exception, and when WaitAll is gathering 
+        /// exceptions for tasks it waited on. If this flag gets set, the implicit wait on children 
+        /// will skip exceptions to prevent duplication.
+        /// 
+        /// This should only be called when this task has completed with an exception
+        /// 
+        /// </summary>
+        internal void UpdateExceptionObservedStatus()
+        {
+            Task parent = m_contingentProperties?.m_parent;
+            if ((parent != null)
+                && ((Options & TaskCreationOptions.AttachedToParent) != 0)
+                && ((parent.CreationOptions & TaskCreationOptions.DenyChildAttach) == 0)
+                && Task.InternalCurrent == parent)
+            {
+                m_stateFlags |= TASK_STATE_EXCEPTIONOBSERVEDBYPARENT;
+            }
+        }
+
+        /// <summary>
+        /// Checks whether the TASK_STATE_EXCEPTIONOBSERVEDBYPARENT status flag is set,
+        /// This will only be used by the implicit wait to prevent double throws
+        /// 
+        /// </summary>
+        internal bool IsExceptionObservedByParent
+        {
+            get
+            {
+                return (m_stateFlags & TASK_STATE_EXCEPTIONOBSERVEDBYPARENT) != 0;
+            }
+        }
+
+        /// <summary>
+        /// Checks whether the body was ever invoked. Used by task scheduler code to verify custom schedulers actually ran the task.
+        /// </summary>
+        internal bool IsDelegateInvoked
+        {
+            get
+            {
+                return (m_stateFlags & TASK_STATE_DELEGATE_INVOKED) != 0;
+            }
+        }
+
+        /// <summary>
+        /// Signals completion of this particular task.
+        ///
+        /// The userDelegateExecute parameter indicates whether this Finish() call comes following the
+        /// full execution of the user delegate. 
+        /// 
+        /// If userDelegateExecute is false, it mean user delegate wasn't invoked at all (either due to
+        /// a cancellation request, or because this task is a promise style Task). In this case, the steps
+        /// involving child tasks (i.e. WaitForChildren) will be skipped.
+        /// 
+        /// </summary>
+        internal void Finish(bool userDelegateExecute)
+        {
+            if (m_contingentProperties == null)
+            {
+                FinishStageTwo();
+            }
+            else
+            {
+                FinishSlow(userDelegateExecute);
+            }
+        }
+
+        private void FinishSlow(bool userDelegateExecute)
+        {
+            Debug.Assert(userDelegateExecute || m_contingentProperties != null);
+
+            if (!userDelegateExecute)
+            {
+                // delegate didn't execute => no children. We can safely call the remaining finish stages
+                FinishStageTwo();
+            }
+            else
+            {
+                ContingentProperties props = m_contingentProperties;
+
+                // Count of 1 => either all children finished, or there were none. Safe to complete ourselves 
+                // without paying the price of an Interlocked.Decrement.
+                if ((props.m_completionCountdown == 1) ||
+                    Interlocked.Decrement(ref props.m_completionCountdown) == 0) // Reaching this sub clause means there may be remaining active children,
+                                                                                 // and we could be racing with one of them to call FinishStageTwo().
+                                                                                 // So whoever does the final Interlocked.Dec is responsible to finish.
+                {
+                    FinishStageTwo();
+                }
+                else
+                {
+                    // Apparently some children still remain. It will be up to the last one to process the completion of this task on their own thread.
+                    // We will now yield the thread back to ThreadPool. Mark our state appropriately before getting out.
+
+                    // We have to use an atomic update for this and make sure not to overwrite a final state, 
+                    // because at this very moment the last child's thread may be concurrently completing us.
+                    // Otherwise we risk overwriting the TASK_STATE_RAN_TO_COMPLETION, _CANCELED or _FAULTED bit which may have been set by that child task.
+                    // Note that the concurrent update by the last child happening in FinishStageTwo could still wipe out the TASK_STATE_WAITING_ON_CHILDREN flag, 
+                    // but it is not critical to maintain, therefore we dont' need to intruduce a full atomic update into FinishStageTwo
+
+                    AtomicStateUpdate(TASK_STATE_WAITING_ON_CHILDREN, TASK_STATE_FAULTED | TASK_STATE_CANCELED | TASK_STATE_RAN_TO_COMPLETION);
+                }
+
+                // Now is the time to prune exceptional children. We'll walk the list and removes the ones whose exceptions we might have observed after they threw.
+                // we use a local variable for exceptional children here because some other thread may be nulling out m_contingentProperties.m_exceptionalChildren 
+                List<Task> exceptionalChildren = props.m_exceptionalChildren;
+                if (exceptionalChildren != null)
+                {
+                    lock (exceptionalChildren)
+                    {
+                        exceptionalChildren.RemoveAll(s_IsExceptionObservedByParentPredicate); // RemoveAll has better performance than doing it ourselves
+                    }
+                }
+            }
+        }
+
+        // statically allocated delegate for the removeall expression in Finish()
+        private readonly static Predicate<Task> s_IsExceptionObservedByParentPredicate = new Predicate<Task>((t) => { return t.IsExceptionObservedByParent; });
+
+        /// <summary>
+        /// FinishStageTwo is to be executed as soon as we known there are no more children to complete. 
+        /// It can happen i) either on the thread that originally executed this task (if no children were spawned, or they all completed by the time this task's delegate quit)
+        ///              ii) or on the thread that executed the last child.
+        /// </summary>
+        private void FinishStageTwo()
+        {
+            // At this point, the task is done executing and waiting for its children,
+            // we can transition our task to a completion state.  
+
+            ContingentProperties cp = Volatile.Read(ref m_contingentProperties);
+            if (cp != null)
+            {
+                AddExceptionsFromChildren(cp);
+            }
+
+            int completionState;
+            if (ExceptionRecorded)
+            {
+                completionState = TASK_STATE_FAULTED;
+                if (DebuggerSupport.LoggingOn)
+                    DebuggerSupport.TraceOperationCompletion(CausalityTraceLevel.Required, this, AsyncStatus.Error);
+                DebuggerSupport.RemoveFromActiveTasks(this);
+            }
+            else if (IsCancellationRequested && IsCancellationAcknowledged)
+            {
+                // We transition into the TASK_STATE_CANCELED final state if the task's CT was signalled for cancellation, 
+                // and the user delegate acknowledged the cancellation request by throwing an OCE, 
+                // and the task hasn't otherwise transitioned into faulted state. (TASK_STATE_FAULTED trumps TASK_STATE_CANCELED)
+                //
+                // If the task threw an OCE without cancellation being requestsed (while the CT not being in signaled state),
+                // then we regard it as a regular exception
+
+                completionState = TASK_STATE_CANCELED;
+                if (DebuggerSupport.LoggingOn)
+                    DebuggerSupport.TraceOperationCompletion(CausalityTraceLevel.Required, this, AsyncStatus.Canceled);
+                DebuggerSupport.RemoveFromActiveTasks(this);
+            }
+            else
+            {
+                completionState = TASK_STATE_RAN_TO_COMPLETION;
+                if (DebuggerSupport.LoggingOn)
+                    DebuggerSupport.TraceOperationCompletion(CausalityTraceLevel.Required, this, AsyncStatus.Completed);
+                DebuggerSupport.RemoveFromActiveTasks(this);
+            }
+
+            // Use Interlocked.Exchange() to effect a memory fence, preventing
+            // any SetCompleted() (or later) instructions from sneak back before it.
+            Interlocked.Exchange(ref m_stateFlags, m_stateFlags | completionState);
+
+            // Set the completion event if it's been lazy allocated.
+            // And if we made a cancellation registration, it's now unnecessary.
+            cp = Volatile.Read(ref m_contingentProperties); // need to re-read after updating state
+            if (cp != null)
+            {
+                cp.SetCompleted();
+                cp.UnregisterCancellationCallback();
+            }
+
+            // ready to run continuations and notify parent.
+            FinishStageThree();
+        }
+
+
+        /// <summary>
+        /// Final stage of the task completion code path. Notifies the parent (if any) that another of its children are done, and runs continuations.
+        /// This function is only separated out from FinishStageTwo because these two operations are also needed to be called from CancellationCleanupLogic()
+        /// </summary>
+        internal void FinishStageThree()
+        {
+            // Release the action so that holding this task object alive doesn't also
+            // hold alive the body of the task.  We do this before notifying a parent,
+            // so that if notifying the parent completes the parent and causes
+            // its synchronous continuations to run, the GC can collect the state
+            // in the interim.  And we do it before finishing continuations, because
+            // continuations hold onto the task, and therefore are keeping it alive.
+            m_action = null;
+
+            ContingentProperties cp = m_contingentProperties;
+            if (cp != null)
+            {
+                // Similarly, null out any ExecutionContext we may have captured,
+                // to avoid keeping state like async locals alive unnecessarily
+                // when the Task is kept alive.
+                cp.m_capturedContext = null;
+
+                // Notify parent if this was an attached task
+                NotifyParentIfPotentiallyAttachedTask();
+            }
+
+            // Activate continuations (if any).
+            FinishContinuations();
+        }
+
+        internal void NotifyParentIfPotentiallyAttachedTask()
+        {
+            Task parent = m_contingentProperties?.m_parent;
+            if (parent != null
+                 && ((parent.CreationOptions & TaskCreationOptions.DenyChildAttach) == 0)
+                 && (((TaskCreationOptions)(m_stateFlags & OptionsMask)) & TaskCreationOptions.AttachedToParent) != 0)
+            {
+                parent.ProcessChildCompletion(this);
+            }
+        }
+
+        /// <summary>
+        /// This is called by children of this task when they are completed.
+        /// </summary>
+        internal void ProcessChildCompletion(Task childTask)
+        {
+            Debug.Assert(childTask != null);
+            Debug.Assert(childTask.IsCompleted, "ProcessChildCompletion was called for an uncompleted task");
+
+            Debug.Assert(childTask.m_contingentProperties?.m_parent == this, "ProcessChildCompletion should only be called for a child of this task");
+
+            var props = Volatile.Read(ref m_contingentProperties);
+
+            // if the child threw and we haven't observed it we need to save it for future reference
+            if (childTask.IsFaulted && !childTask.IsExceptionObservedByParent)
+            {
+                // Lazily initialize the child exception list
+                if (props.m_exceptionalChildren == null)
+                {
+                    Interlocked.CompareExchange(ref props.m_exceptionalChildren, new List<Task>(), null);
+                }
+
+                // In rare situations involving AppDomainUnload, it's possible (though unlikely) for FinishStageTwo() to be called
+                // multiple times for the same task.  In that case, AddExceptionsFromChildren() could be nulling m_exceptionalChildren
+                // out at the same time that we're processing it, resulting in a NullReferenceException here.  We'll protect
+                // ourselves by caching m_exceptionChildren in a local variable.
+                List<Task> tmp = props.m_exceptionalChildren;
+                if (tmp != null)
+                {
+                    lock (tmp)
+                    {
+                        tmp.Add(childTask);
+                    }
+                }
+            }
+
+            if (Interlocked.Decrement(ref props.m_completionCountdown) == 0)
+            {
+                // This call came from the final child to complete, and apparently we have previously given up this task's right to complete itself.
+                // So we need to invoke the final finish stage.
+
+                FinishStageTwo();
+            }
+        }
+
+        /// <summary>
+        /// This is to be called just before the task does its final state transition. 
+        /// It traverses the list of exceptional children, and appends their aggregate exceptions into this one's exception list
+        /// </summary>
+        internal void AddExceptionsFromChildren(ContingentProperties props)
+        {
+            Debug.Assert(props != null);
+
+            // In rare occurences during AppDomainUnload() processing, it is possible for this method to be called
+            // simultaneously on the same task from two different contexts.  This can result in m_exceptionalChildren
+            // being nulled out while it is being processed, which could lead to a NullReferenceException.  To
+            // protect ourselves, we'll cache m_exceptionalChildren in a local variable.
+            List<Task> exceptionalChildren = props.m_exceptionalChildren;
+
+            if (exceptionalChildren != null)
+            {
+                // This lock is necessary because even though AddExceptionsFromChildren is last to execute, it may still 
+                // be racing with the code segment at the bottom of Finish() that prunes the exceptional child array. 
+                lock (exceptionalChildren)
+                {
+                    foreach (Task task in exceptionalChildren)
+                    {
+                        // Ensure any exceptions thrown by children are added to the parent.
+                        // In doing this, we are implicitly marking children as being "handled".
+                        Debug.Assert(task.IsCompleted, "Expected all tasks in list to be completed");
+                        if (task.IsFaulted && !task.IsExceptionObservedByParent)
+                        {
+                            TaskExceptionHolder exceptionHolder = Volatile.Read(ref task.m_contingentProperties).m_exceptionsHolder;
+                            Debug.Assert(exceptionHolder != null);
+
+                            // No locking necessary since child task is finished adding exceptions
+                            // and concurrent CreateExceptionObject() calls do not constitute
+                            // a concurrency hazard.
+                            AddException(exceptionHolder.CreateExceptionObject(false, null));
+                        }
+                    }
+                }
+
+                // Reduce memory pressure by getting rid of the array
+                props.m_exceptionalChildren = null;
+            }
+        }
+
+        /// <summary>
+        /// Outermost entry function to execute this task. Handles all aspects of executing a task on the caller thread.
+        /// </summary>
+        internal bool ExecuteEntry()
+        {
+            // Do atomic state transition from queued to invoked. If we observe a task that's already invoked,
+            // we will return false so that TaskScheduler.ExecuteTask can throw an exception back to the custom scheduler.
+            // However we don't want this exception to be throw if the task was already canceled, because it's a
+            // legitimate scenario for custom schedulers to dequeue a task and mark it as canceled (example: throttling scheduler)
+            int previousState = 0;
+            if (!AtomicStateUpdate(TASK_STATE_DELEGATE_INVOKED,
+                                    TASK_STATE_DELEGATE_INVOKED | TASK_STATE_COMPLETED_MASK,
+                                    ref previousState) && (previousState & TASK_STATE_CANCELED) == 0)
+            {
+                // This task has already been invoked.  Don't invoke it again.
+                return false;
+            }
+
+            if (!IsCancellationRequested & !IsCanceled)
+            {
+                ExecuteWithThreadLocal(ref t_currentTask);
+            }
+            else
+            {
+                ExecuteEntryCancellationRequestedOrCanceled();
+            }
+
+            return true;
+        }
+
+        /// <summary>
+        /// ThreadPool's entry point into the Task.  The base behavior is simply to
+        /// use the entry point that's not protected from double-invoke; derived internal tasks
+        /// can override to customize their behavior, which is usually done by promises
+        /// that want to reuse the same object as a queued work item.
+        /// </summary>
+        internal virtual void ExecuteFromThreadPool(Thread threadPoolThread) => ExecuteEntryUnsafe(threadPoolThread);
+
+        internal void ExecuteEntryUnsafe(Thread threadPoolThread) // used instead of ExecuteEntry() when we don't have to worry about double-execution prevent
+        {
+            // Remember that we started running the task delegate.
+            m_stateFlags |= TASK_STATE_DELEGATE_INVOKED;
+
+            if (!IsCancellationRequested & !IsCanceled)
+            {
+                ExecuteWithThreadLocal(ref t_currentTask, threadPoolThread);
+            }
+            else
+            {
+                ExecuteEntryCancellationRequestedOrCanceled();
+            }
+        }
+
+        internal void ExecuteEntryCancellationRequestedOrCanceled()
+        {
+            if (!IsCanceled)
+            {
+                int prevState = Interlocked.Exchange(ref m_stateFlags, m_stateFlags | TASK_STATE_CANCELED);
+                if ((prevState & TASK_STATE_CANCELED) == 0)
+                {
+                    CancellationCleanupLogic();
+                }
+            }
+        }
+
+        // A trick so we can refer to the TLS slot with a byref.
+        private void ExecuteWithThreadLocal(ref Task currentTaskSlot, Thread threadPoolThread = null)
+        {
+            // Remember the current task so we can restore it after running, and then
+            Task previousTask = currentTaskSlot;
+/*
+            // ETW event for Task Started
+            if (TaskTrace.Enabled)
+            {
+                // previousTask holds the actual "current task" we want to report in the event
+                if (previousTask != null)
+                    TaskTrace.TaskStarted(previousTask.m_taskScheduler.Id, previousTask.Id, this.Id);
+                else
+                    TaskTrace.TaskStarted(TaskScheduler.Current.Id, 0, this.Id);
+            }
+*/
+            if (DebuggerSupport.LoggingOn)
+                DebuggerSupport.TraceSynchronousWorkStart(CausalityTraceLevel.Required, this, CausalitySynchronousWork.Execution);
+
+
+            try
+            {
+                // place the current task into TLS.
+                currentTaskSlot = this;
+
+                // Execute the task body
+                try
+                {
+                    ExecutionContext ec = CapturedContext;
+                    if (ec == null)
+                    {
+                        // No context, just run the task directly.
+                        InnerInvoke();
+                    }
+                    else
+                    {
+                        // Invoke it under the captured ExecutionContext
+                        if (threadPoolThread is null)
+                        {
+                            ExecutionContext.RunInternal(ec, s_ecCallback, this);
+                        }
+                        else
+                        {
+                            ExecutionContext.RunFromThreadPoolDispatchLoop(threadPoolThread, ec, s_ecCallback, this);
+                        }
+                    }
+                }
+                catch (Exception exn)
+                {
+                    // Record this exception in the task's exception list
+                    HandleException(exn);
+                }
+
+                if (DebuggerSupport.LoggingOn)
+                    DebuggerSupport.TraceSynchronousWorkCompletion(CausalityTraceLevel.Required, CausalitySynchronousWork.Execution);
+
+                Finish(true);
+            }
+            finally
+            {
+                currentTaskSlot = previousTask;
+/*
+                // ETW event for Task Completed
+                if (TaskTrace.Enabled)
+                {
+                    // previousTask holds the actual "current task" we want to report in the event
+                    if (previousTask != null)
+                        TaskTrace.TaskCompleted(previousTask.m_taskScheduler.Id, previousTask.Id, this.Id, IsFaulted);
+                    else
+                        TaskTrace.TaskCompleted(TaskScheduler.Current.Id, 0, this.Id, IsFaulted);
+                }
+*/
+            }
+        }
+
+        private static readonly ContextCallback s_ecCallback = obj => ((Task)obj).InnerInvoke();
+
+        /// <summary>
+        /// The actual code which invokes the body of the task. This can be overridden in derived types.
+        /// </summary>
+        internal virtual void InnerInvoke()
+        {
+            // Invoke the delegate
+            Debug.Assert(m_action != null, "Null action in InnerInvoke()");
+            var action = m_action as Action;
+            if (action != null)
+            {
+                action();
+                return;
+            }
+            var actionWithState = m_action as Action<object>;
+            if (actionWithState != null)
+            {
+                actionWithState(m_stateObject);
+                return;
+            }
+            Debug.Fail("Invalid m_action in Task");
+        }
+
+        /// <summary>
+        /// Performs whatever handling is necessary for an unhandled exception. Normally
+        /// this just entails adding the exception to the holder object. 
+        /// </summary>
+        /// <param name="unhandledException">The exception that went unhandled.</param>
+        private void HandleException(Exception unhandledException)
+        {
+            Debug.Assert(unhandledException != null);
+
+            OperationCanceledException exceptionAsOce = unhandledException as OperationCanceledException;
+            if (exceptionAsOce != null && IsCancellationRequested &&
+                m_contingentProperties.m_cancellationToken == exceptionAsOce.CancellationToken)
+            {
+                // All conditions are satisfied for us to go into canceled state in Finish().
+                // Mark the acknowledgement.  The exception is also stored to enable it to be
+                // the exception propagated from an await.
+
+                SetCancellationAcknowledged();
+                AddException(exceptionAsOce, representsCancellation: true);
+            }
+            else
+            {
+                // Other exceptions, including any OCE from the task that doesn't match the tasks' own CT, 
+                // or that gets thrown without the CT being set will be treated as an ordinary exception 
+                // and added to the aggregate.
+
+                AddException(unhandledException);
+            }
+        }
+
+        #region Await Support
+        /// <summary>Gets an awaiter used to await this <see cref="System.Threading.Tasks.Task"/>.</summary>
+        /// <returns>An awaiter instance.</returns>
+        /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
+        public TaskAwaiter GetAwaiter()
+        {
+            return new TaskAwaiter(this);
+        }
+
+        /// <summary>Configures an awaiter used to await this <see cref="System.Threading.Tasks.Task"/>.</summary>
+        /// <param name="continueOnCapturedContext">
+        /// true to attempt to marshal the continuation back to the original context captured; otherwise, false.
+        /// </param>
+        /// <returns>An object used to await this task.</returns>
+        public ConfiguredTaskAwaitable ConfigureAwait(bool continueOnCapturedContext)
+        {
+            return new ConfiguredTaskAwaitable(this, continueOnCapturedContext);
+        }
+
+        /// <summary>
+        /// Sets a continuation onto the <see cref="System.Threading.Tasks.Task"/>.
+        /// The continuation is scheduled to run in the current synchronization context is one exists, 
+        /// otherwise in the current task scheduler.
+        /// </summary>
+        /// <param name="continuationAction">The action to invoke when the <see cref="System.Threading.Tasks.Task"/> has completed.</param>
+        /// <param name="continueOnCapturedContext">
+        /// true to attempt to marshal the continuation back to the original context captured; otherwise, false.
+        /// </param>
+        /// <param name="flowExecutionContext">Whether to flow ExecutionContext across the await.</param>
+        /// <exception cref="System.InvalidOperationException">The awaiter was not properly initialized.</exception>
+        internal void SetContinuationForAwait(
+            Action continuationAction, bool continueOnCapturedContext, bool flowExecutionContext)
+        {
+            Debug.Assert(continuationAction != null);
+
+            // Create the best AwaitTaskContinuation object given the request.
+            // If this remains null by the end of the function, we can use the 
+            // continuationAction directly without wrapping it.
+            TaskContinuation tc = null;
+
+            // If the user wants the continuation to run on the current "context" if there is one...
+            if (continueOnCapturedContext)
+            {
+                // First try getting the current synchronization context.
+                // If the current context is really just the base SynchronizationContext type, 
+                // which is intended to be equivalent to not having a current SynchronizationContext at all, 
+                // then ignore it.  This helps with performance by avoiding unnecessary posts and queueing
+                // of work items, but more so it ensures that if code happens to publish the default context 
+                // as current, it won't prevent usage of a current task scheduler if there is one.
+                var syncCtx = SynchronizationContext.Current;
+                if (syncCtx != null && syncCtx.GetType() != typeof(SynchronizationContext))
+                {
+                    tc = new SynchronizationContextAwaitTaskContinuation(syncCtx, continuationAction, flowExecutionContext);
+                }
+                else
+                {
+                    // If there was no SynchronizationContext, then try for the current scheduler.
+                    // We only care about it if it's not the default.
+                    var scheduler = TaskScheduler.InternalCurrent;
+                    if (scheduler != null && scheduler != TaskScheduler.Default)
+                    {
+                        tc = new TaskSchedulerAwaitTaskContinuation(scheduler, continuationAction, flowExecutionContext);
+                    }
+                }
+            }
+
+            if (tc == null && flowExecutionContext)
+            {
+                // We're targeting the default scheduler, so we can use the faster path
+                // that assumes the default, and thus we don't need to store it.  If we're flowing
+                // ExecutionContext, we need to capture it and wrap it in an AwaitTaskContinuation.
+                // Otherwise, we're targeting the default scheduler and we don't need to flow ExecutionContext, so
+                // we don't actually need a continuation object.  We can just store/queue the action itself.
+                tc = new AwaitTaskContinuation(continuationAction, flowExecutionContext: true);
+            }
+
+            // Now register the continuation, and if we couldn't register it because the task is already completing,
+            // process the continuation directly (in which case make sure we schedule the continuation
+            // rather than inlining it, the latter of which could result in a rare but possible stack overflow).
+            if (tc != null)
+            {
+                if (!AddTaskContinuation(tc, addBeforeOthers: false))
+                    tc.Run(this, canInlineContinuationTask: false);
+            }
+            else
+            {
+                Debug.Assert(!flowExecutionContext, "We already determined we're not required to flow context.");
+                if (!AddTaskContinuation(continuationAction, addBeforeOthers: false))
+                    AwaitTaskContinuation.UnsafeScheduleAction(continuationAction, this);
+            }
+        }
+
+        /// <summary>
+        /// Sets a continuation onto the <see cref="System.Threading.Tasks.Task"/>.
+        /// The continuation is scheduled to run in the current synchronization context is one exists, 
+        /// otherwise in the current task scheduler.
+        /// </summary>
+        /// <param name="stateMachineBox">The action to invoke when the <see cref="System.Threading.Tasks.Task"/> has completed.</param>
+        /// <param name="continueOnCapturedContext">
+        /// true to attempt to marshal the continuation back to the original context captured; otherwise, false.
+        /// </param>
+        /// <exception cref="System.InvalidOperationException">The awaiter was not properly initialized.</exception>
+        internal void UnsafeSetContinuationForAwait(IAsyncStateMachineBox stateMachineBox, bool continueOnCapturedContext)
+        {
+            Debug.Assert(stateMachineBox != null);
+
+            // If the caller wants to continue on the current context/scheduler and there is one,
+            // fall back to using the state machine's delegate.
+            if (continueOnCapturedContext)
+            {
+                SynchronizationContext syncCtx = SynchronizationContext.Current;
+                if (syncCtx != null && syncCtx.GetType() != typeof(SynchronizationContext))
+                {
+                    var tc = new SynchronizationContextAwaitTaskContinuation(syncCtx, stateMachineBox.MoveNextAction, flowExecutionContext: false);
+                    if (!AddTaskContinuation(tc, addBeforeOthers: false))
+                    {
+                        tc.Run(this, canInlineContinuationTask: false);
+                    }
+                    return;
+                }
+                else
+                {
+                    TaskScheduler scheduler = TaskScheduler.InternalCurrent;
+                    if (scheduler != null && scheduler != TaskScheduler.Default)
+                    {
+                        var tc = new TaskSchedulerAwaitTaskContinuation(scheduler, stateMachineBox.MoveNextAction, flowExecutionContext: false);
+                        if (!AddTaskContinuation(tc, addBeforeOthers: false))
+                        {
+                            tc.Run(this, canInlineContinuationTask: false);
+                        }
+                        return;
+                    }
+                }
+            }
+
+            // Otherwise, add the state machine box directly as the ITaskCompletionAction continuation.
+            // If we're unable to because the task has already completed, queue the delegate.
+            if (!AddTaskContinuation(stateMachineBox, addBeforeOthers: false))
+            {
+                AwaitTaskContinuation.UnsafeScheduleAction(stateMachineBox.MoveNextAction, this);
+            }
+        }
+
+        /// <summary>Creates an awaitable that asynchronously yields back to the current context when awaited.</summary>
+        /// <returns>
+        /// A context that, when awaited, will asynchronously transition back into the current context at the 
+        /// time of the await. If the current SynchronizationContext is non-null, that is treated as the current context.
+        /// Otherwise, TaskScheduler.Current is treated as the current context.
+        /// </returns>
+        public static YieldAwaitable Yield()
+        {
+            return new YieldAwaitable();
+        }
+        #endregion
+
+        /// <summary>
+        /// Waits for the <see cref="Task"/> to complete execution.
+        /// </summary>
+        /// <exception cref="T:System.AggregateException">
+        /// The <see cref="Task"/> was canceled -or- an exception was thrown during
+        /// the execution of the <see cref="Task"/>.
+        /// </exception>
+        public void Wait()
+        {
+#if DEBUG
+            bool waitResult =
+#endif
+            Wait(Timeout.Infinite, default);
+
+#if DEBUG
+            Debug.Assert(waitResult, "expected wait to succeed");
+#endif
+        }
+
+        /// <summary>
+        /// Waits for the <see cref="Task"/> to complete execution.
+        /// </summary>
+        /// <param name="timeout">
+        /// A <see cref="System.TimeSpan"/> that represents the number of milliseconds to wait, or a <see
+        /// cref="System.TimeSpan"/> that represents -1 milliseconds to wait indefinitely.
+        /// </param>
+        /// <returns>
+        /// true if the <see cref="Task"/> completed execution within the allotted time; otherwise, false.
+        /// </returns>
+        /// <exception cref="T:System.AggregateException">
+        /// The <see cref="Task"/> was canceled -or- an exception was thrown during the execution of the <see
+        /// cref="Task"/>.
+        /// </exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">
+        /// <paramref name="timeout"/> is a negative number other than -1 milliseconds, which represents an
+        /// infinite time-out -or- timeout is greater than
+        /// <see cref="System.Int32.MaxValue"/>.
+        /// </exception>
+        public bool Wait(TimeSpan timeout)
+        {
+            long totalMilliseconds = (long)timeout.TotalMilliseconds;
+            if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue)
+            {
+                ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.timeout);
+            }
+
+            return Wait((int)totalMilliseconds, default);
+        }
+
+
+        /// <summary>
+        /// Waits for the <see cref="Task"/> to complete execution.
+        /// </summary>
+        /// <param name="cancellationToken">
+        /// A <see cref="CancellationToken"/> to observe while waiting for the task to complete.
+        /// </param>
+        /// <exception cref="T:System.OperationCanceledException">
+        /// The <paramref name="cancellationToken"/> was canceled.
+        /// </exception>
+        /// <exception cref="T:System.AggregateException">
+        /// The <see cref="Task"/> was canceled -or- an exception was thrown during the execution of the <see
+        /// cref="Task"/>.
+        /// </exception>
+        public void Wait(CancellationToken cancellationToken)
+        {
+            Wait(Timeout.Infinite, cancellationToken);
+        }
+
+
+        /// <summary>
+        /// Waits for the <see cref="Task"/> to complete execution.
+        /// </summary>
+        /// <param name="millisecondsTimeout">
+        /// The number of milliseconds to wait, or <see cref="System.Threading.Timeout.Infinite"/> (-1) to
+        /// wait indefinitely.</param>
+        /// <returns>true if the <see cref="Task"/> completed execution within the allotted time; otherwise,
+        /// false.
+        /// </returns>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">
+        /// <paramref name="millisecondsTimeout"/> is a negative number other than -1, which represents an
+        /// infinite time-out.
+        /// </exception>
+        /// <exception cref="T:System.AggregateException">
+        /// The <see cref="Task"/> was canceled -or- an exception was thrown during the execution of the <see
+        /// cref="Task"/>.
+        /// </exception>
+        public bool Wait(int millisecondsTimeout)
+        {
+            return Wait(millisecondsTimeout, default);
+        }
+
+
+        /// <summary>
+        /// Waits for the <see cref="Task"/> to complete execution.
+        /// </summary>
+        /// <param name="millisecondsTimeout">
+        /// The number of milliseconds to wait, or <see cref="System.Threading.Timeout.Infinite"/> (-1) to
+        /// wait indefinitely.
+        /// </param>
+        /// <param name="cancellationToken">
+        /// A <see cref="CancellationToken"/> to observe while waiting for the task to complete.
+        /// </param>
+        /// <returns>
+        /// true if the <see cref="Task"/> completed execution within the allotted time; otherwise, false.
+        /// </returns>
+        /// <exception cref="T:System.AggregateException">
+        /// The <see cref="Task"/> was canceled -or- an exception was thrown during the execution of the <see
+        /// cref="Task"/>.
+        /// </exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">
+        /// <paramref name="millisecondsTimeout"/> is a negative number other than -1, which represents an
+        /// infinite time-out.
+        /// </exception>
+        /// <exception cref="T:System.OperationCanceledException">
+        /// The <paramref name="cancellationToken"/> was canceled.
+        /// </exception>
+        public bool Wait(int millisecondsTimeout, CancellationToken cancellationToken)
+        {
+            if (millisecondsTimeout < -1)
+            {
+                ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.millisecondsTimeout);
+            }
+
+            // Return immediately if we know that we've completed "clean" -- no exceptions, no cancellations
+            // and if no notification to the debugger is required
+            if (!IsWaitNotificationEnabledOrNotRanToCompletion) // (!DebuggerBitSet && RanToCompletion)
+                return true;
+
+            // Wait, and then return if we're still not done.
+            if (!InternalWait(millisecondsTimeout, cancellationToken))
+                return false;
+
+            if (IsWaitNotificationEnabledOrNotRanToCompletion) // avoid a few unnecessary volatile reads if we completed successfully
+            {
+                // Notify the debugger of the wait completion if it's requested such a notification
+                NotifyDebuggerOfWaitCompletionIfNecessary();
+
+                // If cancellation was requested and the task was canceled, throw an 
+                // OperationCanceledException.  This is prioritized ahead of the ThrowIfExceptional
+                // call to bring more determinism to cases where the same token is used to 
+                // cancel the Wait and to cancel the Task.  Otherwise, there's a race condition between
+                // whether the Wait or the Task observes the cancellation request first,
+                // and different exceptions result from the different cases.
+                if (IsCanceled) cancellationToken.ThrowIfCancellationRequested();
+
+                // If an exception occurred, or the task was cancelled, throw an exception.
+                ThrowIfExceptional(true);
+            }
+
+            Debug.Assert((m_stateFlags & TASK_STATE_FAULTED) == 0, "Task.Wait() completing when in Faulted state.");
+
+            return true;
+        }
+
+        // Convenience method that wraps any scheduler exception in a TaskSchedulerException
+        // and rethrows it.
+        private bool WrappedTryRunInline()
+        {
+            if (m_taskScheduler == null)
+                return false;
+
+            try
+            {
+                return m_taskScheduler.TryRunInline(this, true);
+            }
+            catch (Exception e)
+            {
+                // we 1) either received an unexpected exception originating from a custom scheduler, which needs to be wrapped in a TSE and thrown
+                //    2) or a a ThreadAbortException, which we need to skip here, because it would already have been handled in Task.Execute
+                //if (!(e is ThreadAbortException))
+                {
+                    TaskSchedulerException tse = new TaskSchedulerException(e);
+                    throw tse;
+                }
+                //else
+                //{
+                //    throw;
+                //}
+            }
+        }
+
+        /// <summary>
+        /// The core wait function, which is only accessible internally. It's meant to be used in places in TPL code where 
+        /// the current context is known or cached.
+        /// </summary>
+        [MethodImpl(MethodImplOptions.NoOptimization)]  // this is needed for the parallel debugger
+        internal bool InternalWait(int millisecondsTimeout, CancellationToken cancellationToken) =>
+            InternalWaitCore(millisecondsTimeout, cancellationToken);
+
+        // Separated out to allow it to be optimized (caller is marked NoOptimization for VS parallel debugger
+        // to be able to see the method on the stack and inspect arguments).
+        private bool InternalWaitCore(int millisecondsTimeout, CancellationToken cancellationToken)
+        {
+            // If the task has already completed, there's nothing to wait for.
+            bool returnValue = IsCompleted;
+            if (returnValue)
+            {
+                return true;
+            }
+/*
+            // ETW event for Task Wait Begin
+            if (TaskTrace.Enabled)
+            {
+                Task currentTask = Task.InternalCurrent;
+                TaskTrace.TaskWaitBegin_Synchronous(
+                    (currentTask != null ? currentTask.m_taskScheduler.Id : TaskScheduler.Default.Id), (currentTask != null ? currentTask.Id : 0),
+                    this.Id);
+            }
+*/
+            // Alert a listening debugger that we can't make forward progress unless it slips threads.
+            // We call NOCTD for two reasons:
+            //    1. If the task runs on another thread, then we'll be blocked here indefinitely.
+            //    2. If the task runs inline but takes some time to complete, it will suffer ThreadAbort with possible state corruption,
+            //       and it is best to prevent this unless the user explicitly asks to view the value with thread-slipping enabled.
+            Debugger.NotifyOfCrossThreadDependency();
+
+            // We will attempt inline execution only if an infinite wait was requested
+            // Inline execution doesn't make sense for finite timeouts and if a cancellation token was specified
+            // because we don't know how long the task delegate will take.
+            if (millisecondsTimeout == Timeout.Infinite && !cancellationToken.CanBeCanceled &&
+                WrappedTryRunInline() && IsCompleted) // TryRunInline doesn't guarantee completion, as there may be unfinished children.
+            {
+                returnValue = true;
+            }
+            else
+            {
+                returnValue = SpinThenBlockingWait(millisecondsTimeout, cancellationToken);
+            }
+
+            Debug.Assert(IsCompleted || millisecondsTimeout != Timeout.Infinite);
+/*
+            // ETW event for Task Wait End
+            if (TaskTrace.Enabled)
+            {
+                Task currentTask = Task.InternalCurrent;
+                if (currentTask != null)
+                {
+                    TaskTrace.TaskWaitEnd(currentTask.m_taskScheduler.Id, currentTask.Id, this.Id);
+                }
+                else
+                {
+                    TaskTrace.TaskWaitEnd(TaskScheduler.Default.Id, 0, this.Id);
+                }
+            }
+*/
+            return returnValue;
+        }
+
+        // An MRES that gets set when Invoke is called.  This replaces old logic that looked like this:
+        //      ManualResetEventSlim mres = new ManualResetEventSlim(false, 0);
+        //      Action<Task> completionAction = delegate {mres.Set();}
+        //      AddCompletionAction(completionAction);
+        // with this:
+        //      SetOnInvokeMres mres = new SetOnInvokeMres();
+        //      AddCompletionAction(mres, addBeforeOthers: true);
+        // which saves a couple of allocations.
+        //
+        // Used in SpinThenBlockingWait (below), but could be seen as a general purpose mechanism.
+        private sealed class SetOnInvokeMres : ManualResetEventSlim, ITaskCompletionAction
+        {
+            internal SetOnInvokeMres() : base(false, 0) { }
+            public void Invoke(Task completingTask) { Set(); }
+            public bool InvokeMayRunArbitraryCode { get { return false; } }
+        }
+
+        /// <summary>
+        /// Waits for the task to complete, for a timeout to occur, or for cancellation to be requested.
+        /// The method first spins and then falls back to blocking on a new event.
+        /// </summary>
+        /// <param name="millisecondsTimeout">The timeout.</param>
+        /// <param name="cancellationToken">The token.</param>
+        /// <returns>true if the task is completed; otherwise, false.</returns>
+        private bool SpinThenBlockingWait(int millisecondsTimeout, CancellationToken cancellationToken)
+        {
+            bool infiniteWait = millisecondsTimeout == Timeout.Infinite;
+            uint startTimeTicks = infiniteWait ? 0 : (uint)Environment.TickCount;
+            bool returnValue = SpinWait(millisecondsTimeout);
+            if (!returnValue)
+            {
+                var mres = new SetOnInvokeMres();
+                try
+                {
+                    AddCompletionAction(mres, addBeforeOthers: true);
+                    if (infiniteWait)
+                    {
+                        returnValue = mres.Wait(Timeout.Infinite, cancellationToken);
+                    }
+                    else
+                    {
+                        uint elapsedTimeTicks = ((uint)Environment.TickCount) - startTimeTicks;
+                        if (elapsedTimeTicks < millisecondsTimeout)
+                        {
+                            returnValue = mres.Wait((int)(millisecondsTimeout - elapsedTimeTicks), cancellationToken);
+                        }
+                    }
+                }
+                finally
+                {
+                    if (!IsCompleted) RemoveContinuation(mres);
+                    // Don't Dispose of the MRES, because the continuation off of this task may
+                    // still be running.  This is ok, however, as we never access the MRES' WaitHandle,
+                    // and thus no finalizable resources are actually allocated.
+                }
+            }
+            return returnValue;
+        }
+
+        /// <summary>
+        /// Spins briefly while checking IsCompleted
+        /// </summary>
+        /// <param name="millisecondsTimeout">The timeout.</param>
+        /// <returns>true if the task is completed; otherwise, false.</returns>
+        /// <exception cref="System.OperationCanceledException">The wait was canceled.</exception>
+        private bool SpinWait(int millisecondsTimeout)
+        {
+            if (IsCompleted) return true;
+
+            if (millisecondsTimeout == 0)
+            {
+                // For 0-timeouts, we just return immediately.
+                return false;
+            }
+
+            int spinCount = Threading.SpinWait.SpinCountforSpinBeforeWait;
+            var spinner = new SpinWait();
+            while (spinner.Count < spinCount)
+            {
+                spinner.SpinOnce(sleep1Threshold: -1);
+
+                if (IsCompleted)
+                {
+                    return true;
+                }
+            }
+
+            return false;
+        }
+
+        /// <summary>
+        /// Cancels the <see cref="Task"/>.
+        /// </summary>
+        /// <param name="bCancelNonExecutingOnly"> 
+        /// Indicates whether we should only cancel non-invoked tasks.
+        /// For the default scheduler this option will only be serviced through TryDequeue.
+        /// For custom schedulers we also attempt an atomic state transition.
+        /// </param>
+        /// <returns>true if the task was successfully canceled; otherwise, false.</returns>
+        internal bool InternalCancel(bool bCancelNonExecutingOnly)
+        {
+            Debug.Assert((Options & (TaskCreationOptions)InternalTaskOptions.PromiseTask) == 0, "Task.InternalCancel() did not expect promise-style task");
+
+            bool bPopSucceeded = false;
+            bool mustCleanup = false;
+
+            TaskSchedulerException tse = null;
+
+            // If started, and running in a task context, we can try to pop the chore.
+            if ((m_stateFlags & TASK_STATE_STARTED) != 0)
+            {
+                TaskScheduler ts = m_taskScheduler;
+
+                try
+                {
+                    bPopSucceeded = (ts != null) && ts.TryDequeue(this);
+                }
+                catch (Exception e)
+                {
+                    // TryDequeue threw. We don't know whether the task was properly dequeued or not. So we must let the rest of 
+                    // the cancellation logic run its course (record the request, attempt atomic state transition and do cleanup where appropriate)
+                    // Here we will only record a TaskSchedulerException, which will later be thrown at function exit.
+
+                    //if (!(e is ThreadAbortException))
+                    {
+                        tse = new TaskSchedulerException(e);
+                    }
+                }
+
+                bool bRequiresAtomicStartTransition = ts != null && ts.RequiresAtomicStartTransition;
+
+                if (!bPopSucceeded && bCancelNonExecutingOnly && bRequiresAtomicStartTransition)
+                {
+                    // The caller requested cancellation of non-invoked tasks only, and TryDequeue was one way of doing it...
+                    // Since that seems to have failed, we should now try an atomic state transition (from non-invoked state to canceled)
+                    // An atomic transition here is only safe if we know we're on a custom task scheduler, which also forces a CAS on ExecuteEntry
+
+                    // Even though this task can't have any children, we should be ready for handling any continuations that 
+                    // may be attached to it (although currently 
+                    // So we need to remeber whether we actually did the flip, so we can do clean up (finish continuations etc)
+                    mustCleanup = AtomicStateUpdate(TASK_STATE_CANCELED, TASK_STATE_DELEGATE_INVOKED | TASK_STATE_CANCELED);
+
+                    // PS: This is slightly different from the regular cancellation codepath 
+                    // since we record the cancellation request *after* doing the state transition. 
+                    // However that shouldn't matter too much because the task was never invoked, thus can't have children
+                }
+            }
+
+            if (!bCancelNonExecutingOnly || bPopSucceeded || mustCleanup)
+            {
+                // Record the cancellation request.
+                RecordInternalCancellationRequest();
+
+                // Determine whether we need to clean up
+                // This will be the case 
+                //     1) if we were able to pop, and we are able to update task state to TASK_STATE_CANCELED
+                //     2) if the task seems to be yet unstarted, and we can transition to
+                //        TASK_STATE_CANCELED before anyone else can transition into _STARTED or _CANCELED or 
+                //        _RAN_TO_COMPLETION or _FAULTED
+                // Note that we do not check for TASK_STATE_COMPLETION_RESERVED.  That only applies to promise-style
+                // tasks, and a promise-style task should not enter into this codepath.
+                if (bPopSucceeded)
+                {
+                    // hitting this would mean something wrong with the AtomicStateUpdate above
+                    Debug.Assert(!mustCleanup, "Possibly an invalid state transition call was made in InternalCancel()");
+
+                    // Include TASK_STATE_DELEGATE_INVOKED in "illegal" bits to protect against the situation where
+                    // TS.TryDequeue() returns true but the task is still left on the queue.
+                    mustCleanup = AtomicStateUpdate(TASK_STATE_CANCELED, TASK_STATE_CANCELED | TASK_STATE_DELEGATE_INVOKED);
+                }
+                else if (!mustCleanup && (m_stateFlags & TASK_STATE_STARTED) == 0)
+                {
+                    mustCleanup = AtomicStateUpdate(TASK_STATE_CANCELED,
+                        TASK_STATE_CANCELED | TASK_STATE_STARTED | TASK_STATE_RAN_TO_COMPLETION |
+                        TASK_STATE_FAULTED | TASK_STATE_DELEGATE_INVOKED);
+                }
+
+                // do the cleanup (i.e. set completion event and finish continuations)
+                if (mustCleanup)
+                {
+                    CancellationCleanupLogic();
+                }
+            }
+
+            if (tse != null)
+                throw tse;
+            else
+                return (mustCleanup);
+        }
+
+        // Breaks out logic for recording a cancellation request
+        internal void RecordInternalCancellationRequest()
+        {
+            // Record the cancellation request.
+            EnsureContingentPropertiesInitialized().m_internalCancellationRequested = CANCELLATION_REQUESTED;
+        }
+
+        // Breaks out logic for recording a cancellation request
+        // This overload should only be used for promise tasks where no cancellation token
+        // was supplied when the task was created.
+        internal void RecordInternalCancellationRequest(CancellationToken tokenToRecord)
+        {
+            RecordInternalCancellationRequest();
+
+            Debug.Assert((Options & (TaskCreationOptions)InternalTaskOptions.PromiseTask) != 0, "Task.RecordInternalCancellationRequest(CancellationToken) only valid for promise-style task");
+            Debug.Assert(m_contingentProperties.m_cancellationToken == default);
+
+            // Store the supplied cancellation token as this task's token.
+            // Waiting on this task will then result in an OperationCanceledException containing this token.
+            if (tokenToRecord != default)
+            {
+                m_contingentProperties.m_cancellationToken = tokenToRecord;
+            }
+        }
+
+        // Breaks out logic for recording a cancellation request
+        // This overload should only be used for promise tasks where no cancellation token
+        // was supplied when the task was created.
+        internal void RecordInternalCancellationRequest(CancellationToken tokenToRecord, object cancellationException)
+        {
+            RecordInternalCancellationRequest(tokenToRecord);
+
+            // Store the supplied cancellation exception
+            if (cancellationException != null)
+            {
+#if DEBUG
+                var oce = cancellationException as OperationCanceledException;
+                if (oce == null)
+                {
+                    var edi = cancellationException as ExceptionDispatchInfo;
+                    Debug.Assert(edi != null, "Expected either an OCE or an EDI");
+                    oce = edi.SourceException as OperationCanceledException;
+                    Debug.Assert(oce != null, "Expected EDI to contain an OCE");
+                }
+                Debug.Assert(oce.CancellationToken == tokenToRecord,
+                                "Expected OCE's token to match the provided token.");
+#endif
+                AddException(cancellationException, representsCancellation: true);
+            }
+        }
+
+        // ASSUMES THAT A SUCCESSFUL CANCELLATION HAS JUST OCCURRED ON THIS TASK!!!
+        // And this method should be called at most once per task.
+        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
+            // 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);
+
+            // Fire completion event if it has been lazily initialized
+            var cp = Volatile.Read(ref m_contingentProperties);
+            if (cp != null)
+            {
+                cp.SetCompleted();
+                cp.UnregisterCancellationCallback();
+            }
+
+            if (DebuggerSupport.LoggingOn)
+                DebuggerSupport.TraceOperationCompletion(CausalityTraceLevel.Required, this, AsyncStatus.Canceled);
+            DebuggerSupport.RemoveFromActiveTasks(this);
+
+            // Notify parents, fire continuations, other cleanup.
+            FinishStageThree();
+        }
+
+
+        /// <summary>
+        /// Sets the task's cancellation acknowledged flag.
+        /// </summary>    
+        private void SetCancellationAcknowledged()
+        {
+            Debug.Assert(this == Task.InternalCurrent, "SetCancellationAcknowledged() should only be called while this is still the current task");
+            Debug.Assert(IsCancellationRequested, "SetCancellationAcknowledged() should not be called if the task's CT wasn't signaled");
+
+            m_stateFlags |= TASK_STATE_CANCELLATIONACKNOWLEDGED;
+        }
+
+
+        //
+        // Continuation passing functionality (aka ContinueWith)
+        //
+
+
+        /// <summary>
+        /// Runs all of the continuations, as appropriate.
+        /// </summary>
+        internal void FinishContinuations()
+        {
+            // Atomically store the fact that this task is completing.  From this point on, the adding of continuations will
+            // result in the continuations being run/launched directly rather than being added to the continuation list.
+            // Then if we grabbed any continuations, run them.
+            object continuationObject = Interlocked.Exchange(ref m_continuationObject, s_taskCompletionSentinel);
+            if (continuationObject != null)
+            {
+                RunContinuations(continuationObject);
+            }
+        }
+
+        private void RunContinuations(object continuationObject) // separated out of FinishContinuations to enable it to be inlined
+        {
+            Debug.Assert(continuationObject != null);
+
+            if (DebuggerSupport.LoggingOn)
+                DebuggerSupport.TraceSynchronousWorkStart(CausalityTraceLevel.Required, this, CausalitySynchronousWork.CompletionNotification);
+
+            // Skip synchronous execution of continuations if this task's thread was aborted
+            bool canInlineContinuations = !(((m_stateFlags & TASK_STATE_THREAD_WAS_ABORTED) != 0) ||
+                                             //(RuntimeThread.CurrentThread.ThreadState == ThreadState.AbortRequested) ||
+                                             ((m_stateFlags & (int)TaskCreationOptions.RunContinuationsAsynchronously) != 0));
+
+            switch (continuationObject)
+            {
+                // Handle the single IAsyncStateMachineBox case.  This could be handled as part of the ITaskCompletionAction
+                // but we want to ensure that inlining is properly handled in the face of schedulers, so its behavior
+                // needs to be customized ala raw Actions.  This is also the most important case, as it represents the
+                // most common form of continuation, so we check it first.
+                case IAsyncStateMachineBox stateMachineBox:
+                    AwaitTaskContinuation.RunOrScheduleAction(stateMachineBox, canInlineContinuations);
+                    LogFinishCompletionNotification();
+                    return;
+
+                // Handle the single Action case.
+                case Action action:
+                    AwaitTaskContinuation.RunOrScheduleAction(action, canInlineContinuations);
+                    LogFinishCompletionNotification();
+                    return;
+
+                // Handle the single TaskContinuation case.
+                case TaskContinuation tc:
+                    tc.Run(this, canInlineContinuations);
+                    LogFinishCompletionNotification();
+                    return;
+
+                // Handle the single ITaskCompletionAction case.
+                case ITaskCompletionAction completionAction:
+                    RunOrQueueCompletionAction(completionAction, canInlineContinuations);
+                    LogFinishCompletionNotification();
+                    return;
+            }
+
+            // Not a single; it must be a list.
+            List<object> continuations = (List<object>)continuationObject;
+
+            //
+            // Begin processing of continuation list
+            //
+
+            // Wait for any concurrent adds or removes to be retired
+            lock (continuations) { }
+            int continuationCount = continuations.Count;
+
+            // Fire the asynchronous continuations first ...
+            for (int i = 0; i < continuationCount; i++)
+            {
+                // Synchronous continuation tasks will have the ExecuteSynchronously option,
+                // and we're looking for asynchronous tasks...
+                if (continuations[i] is StandardTaskContinuation tc &&
+                    (tc.m_options & TaskContinuationOptions.ExecuteSynchronously) == 0)
+                {
+                    continuations[i] = null; // so that we can skip this later
+                    tc.Run(this, canInlineContinuations);
+                }
+            }
+
+            // ... and then fire the synchronous continuations (if there are any).
+            // This includes ITaskCompletionAction, AwaitTaskContinuations, IAsyncStateMachineBox,
+            // and Action delegates, which are all by default implicitly synchronous.
+            for (int i = 0; i < continuationCount; i++)
+            {
+                object currentContinuation = continuations[i];
+                if (currentContinuation == null)
+                {
+                    continue;
+                }
+                continuations[i] = null; // to enable free'ing up memory earlier
+
+                switch (currentContinuation)
+                {
+                    case IAsyncStateMachineBox stateMachineBox:
+                        AwaitTaskContinuation.RunOrScheduleAction(stateMachineBox, canInlineContinuations);
+                        break;
+
+                    case Action action:
+                        AwaitTaskContinuation.RunOrScheduleAction(action, canInlineContinuations);
+                        break;
+
+                    case TaskContinuation tc:
+                        tc.Run(this, canInlineContinuations);
+                        break;
+
+                    default:
+                        Debug.Assert(currentContinuation is ITaskCompletionAction);
+                        RunOrQueueCompletionAction((ITaskCompletionAction)currentContinuation, canInlineContinuations);
+                        break;
+                }
+            }
+
+            LogFinishCompletionNotification();
+        }
+
+        private void RunOrQueueCompletionAction(ITaskCompletionAction completionAction, bool allowInlining)
+        {
+            if (allowInlining || !completionAction.InvokeMayRunArbitraryCode)
+            {
+                completionAction.Invoke(this);
+            }
+            else
+            {
+                ThreadPool.UnsafeQueueUserWorkItemInternal(new CompletionActionInvoker(completionAction, this), preferLocal: true);
+            }
+        }
+
+        [MethodImpl(MethodImplOptions.AggressiveInlining)]
+        private void LogFinishCompletionNotification()
+        {
+            if (DebuggerSupport.LoggingOn)
+                DebuggerSupport.TraceSynchronousWorkCompletion(CausalityTraceLevel.Required, CausalitySynchronousWork.CompletionNotification);
+        }
+
+        #region Continuation methods
+
+        #region Action<Task> continuation
+        /// <summary>
+        /// Creates a continuation that executes when the target <see cref="Task"/> completes.
+        /// </summary>
+        /// <param name="continuationAction">
+        /// An action to run when the <see cref="Task"/> completes. When run, the delegate will be
+        /// passed the completed task as an argument.
+        /// </param>
+        /// <returns>A new continuation <see cref="Task"/>.</returns>
+        /// <remarks>
+        /// The returned <see cref="Task"/> will not be scheduled for execution until the current task has
+        /// completed, whether it completes due to running to completion successfully, faulting due to an
+        /// unhandled exception, or exiting out early due to being canceled.
+        /// </remarks>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="continuationAction"/> argument is null.
+        /// </exception>
+        public Task ContinueWith(Action<Task> continuationAction)
+        {
+            return ContinueWith(continuationAction, TaskScheduler.Current, default, TaskContinuationOptions.None);
+        }
+
+        /// <summary>
+        /// Creates a continuation that executes when the target <see cref="Task"/> completes.
+        /// </summary>
+        /// <param name="continuationAction">
+        /// An action to run when the <see cref="Task"/> completes. When run, the delegate will be
+        /// passed the completed task as an argument.
+        /// </param>
+        /// <param name="cancellationToken"> The <see cref="CancellationToken"/> that will be assigned to the new continuation task.</param>
+        /// <returns>A new continuation <see cref="Task"/>.</returns>
+        /// <remarks>
+        /// The returned <see cref="Task"/> will not be scheduled for execution until the current task has
+        /// completed, whether it completes due to running to completion successfully, faulting due to an
+        /// unhandled exception, or exiting out early due to being canceled.
+        /// </remarks>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="continuationAction"/> argument is null.
+        /// </exception>
+        /// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
+        /// has already been disposed.
+        /// </exception>
+        public Task ContinueWith(Action<Task> continuationAction, CancellationToken cancellationToken)
+        {
+            return ContinueWith(continuationAction, TaskScheduler.Current, cancellationToken, TaskContinuationOptions.None);
+        }
+
+        /// <summary>
+        /// Creates a continuation that executes when the target <see cref="Task"/> completes.
+        /// </summary>
+        /// <param name="continuationAction">
+        /// An action to run when the <see cref="Task"/> completes.  When run, the delegate will be
+        /// passed the completed task as an argument.
+        /// </param>
+        /// <param name="scheduler">
+        /// The <see cref="TaskScheduler"/> to associate with the continuation task and to use for its execution.
+        /// </param>
+        /// <returns>A new continuation <see cref="Task"/>.</returns>
+        /// <remarks>
+        /// The returned <see cref="Task"/> will not be scheduled for execution until the current task has
+        /// completed, whether it completes due to running to completion successfully, faulting due to an
+        /// unhandled exception, or exiting out early due to being canceled.
+        /// </remarks>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="continuationAction"/> argument is null.
+        /// </exception>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="scheduler"/> argument is null.
+        /// </exception>
+        public Task ContinueWith(Action<Task> continuationAction, TaskScheduler scheduler)
+        {
+            return ContinueWith(continuationAction, scheduler, default, TaskContinuationOptions.None);
+        }
+
+        /// <summary>
+        /// Creates a continuation that executes when the target <see cref="Task"/> completes.
+        /// </summary>
+        /// <param name="continuationAction">
+        /// An action to run when the <see cref="Task"/> completes. When run, the delegate will be
+        /// passed the completed task as an argument.
+        /// </param>
+        /// <param name="continuationOptions">
+        /// Options for when the continuation is scheduled and how it behaves. This includes criteria, such
+        /// as <see
+        /// cref="System.Threading.Tasks.TaskContinuationOptions.OnlyOnCanceled">OnlyOnCanceled</see>, as
+        /// well as execution options, such as <see
+        /// cref="System.Threading.Tasks.TaskContinuationOptions.ExecuteSynchronously">ExecuteSynchronously</see>.
+        /// </param>
+        /// <returns>A new continuation <see cref="Task"/>.</returns>
+        /// <remarks>
+        /// The returned <see cref="Task"/> will not be scheduled for execution until the current task has
+        /// completed. If the continuation criteria specified through the <paramref
+        /// name="continuationOptions"/> parameter are not met, the continuation task will be canceled
+        /// instead of scheduled.
+        /// </remarks>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="continuationAction"/> argument is null.
+        /// </exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">
+        /// The <paramref name="continuationOptions"/> argument specifies an invalid value for <see
+        /// cref="T:System.Threading.Tasks.TaskContinuationOptions">TaskContinuationOptions</see>.
+        /// </exception>
+        public Task ContinueWith(Action<Task> continuationAction, TaskContinuationOptions continuationOptions)
+        {
+            return ContinueWith(continuationAction, TaskScheduler.Current, default, continuationOptions);
+        }
+
+        /// <summary>
+        /// Creates a continuation that executes when the target <see cref="Task"/> completes.
+        /// </summary>
+        /// <param name="continuationAction">
+        /// An action to run when the <see cref="Task"/> completes. When run, the delegate will be
+        /// passed the completed task as an argument.
+        /// </param>
+        /// <param name="continuationOptions">
+        /// Options for when the continuation is scheduled and how it behaves. This includes criteria, such
+        /// as <see
+        /// cref="System.Threading.Tasks.TaskContinuationOptions.OnlyOnCanceled">OnlyOnCanceled</see>, as
+        /// well as execution options, such as <see
+        /// cref="System.Threading.Tasks.TaskContinuationOptions.ExecuteSynchronously">ExecuteSynchronously</see>.
+        /// </param>
+        /// <param name="cancellationToken">The <see cref="CancellationToken"/> that will be assigned to the new continuation task.</param>
+        /// <param name="scheduler">
+        /// The <see cref="TaskScheduler"/> to associate with the continuation task and to use for its
+        /// execution.
+        /// </param>
+        /// <returns>A new continuation <see cref="Task"/>.</returns>
+        /// <remarks>
+        /// The returned <see cref="Task"/> will not be scheduled for execution until the current task has
+        /// completed. If the criteria specified through the <paramref name="continuationOptions"/> parameter
+        /// are not met, the continuation task will be canceled instead of scheduled.
+        /// </remarks>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="continuationAction"/> argument is null.
+        /// </exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">
+        /// The <paramref name="continuationOptions"/> argument specifies an invalid value for <see
+        /// cref="T:System.Threading.Tasks.TaskContinuationOptions">TaskContinuationOptions</see>.
+        /// </exception>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="scheduler"/> argument is null.
+        /// </exception>
+        /// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
+        /// has already been disposed.
+        /// </exception>
+        public Task ContinueWith(Action<Task> continuationAction, CancellationToken cancellationToken,
+                                 TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
+        {
+            return ContinueWith(continuationAction, scheduler, cancellationToken, continuationOptions);
+        }
+
+        // Same as the above overload, just with a stack mark parameter.
+        private Task ContinueWith(Action<Task> continuationAction, TaskScheduler scheduler,
+            CancellationToken cancellationToken, TaskContinuationOptions continuationOptions)
+        {
+            // Throw on continuation with null action
+            if (continuationAction == null)
+            {
+                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationAction);
+            }
+
+            // Throw on continuation with null TaskScheduler
+            if (scheduler == null)
+            {
+                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler);
+            }
+
+            TaskCreationOptions creationOptions;
+            InternalTaskOptions internalOptions;
+            CreationOptionsFromContinuationOptions(continuationOptions, out creationOptions, out internalOptions);
+
+            Task continuationTask = new ContinuationTaskFromTask(
+                this, continuationAction, null,
+                creationOptions, internalOptions
+            );
+
+            // Register the continuation.  If synchronous execution is requested, this may
+            // actually invoke the continuation before returning.
+            ContinueWithCore(continuationTask, scheduler, cancellationToken, continuationOptions);
+
+            return continuationTask;
+        }
+        #endregion
+
+        #region Action<Task, Object> continuation
+
+        /// <summary>
+        /// Creates a continuation that executes when the target <see cref="Task"/> completes.
+        /// </summary>
+        /// <param name="continuationAction">
+        /// An action to run when the <see cref="Task"/> completes. When run, the delegate will be
+        /// passed the completed task as and the caller-supplied state object as arguments.
+        /// </param>
+        /// <param name="state">An object representing data to be used by the continuation action.</param>
+        /// <returns>A new continuation <see cref="Task"/>.</returns>
+        /// <remarks>
+        /// The returned <see cref="Task"/> will not be scheduled for execution until the current task has
+        /// completed, whether it completes due to running to completion successfully, faulting due to an
+        /// unhandled exception, or exiting out early due to being canceled.
+        /// </remarks>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="continuationAction"/> argument is null.
+        /// </exception>
+        public Task ContinueWith(Action<Task, object> continuationAction, object state)
+        {
+            return ContinueWith(continuationAction, state, TaskScheduler.Current, default, TaskContinuationOptions.None);
+        }
+
+        /// <summary>
+        /// Creates a continuation that executes when the target <see cref="Task"/> completes.
+        /// </summary>
+        /// <param name="continuationAction">
+        /// An action to run when the <see cref="Task"/> completes. When run, the delegate will be
+        /// passed the completed task and the caller-supplied state object as arguments.
+        /// </param>
+        /// <param name="state">An object representing data to be used by the continuation action.</param>
+        /// <param name="cancellationToken"> The <see cref="CancellationToken"/> that will be assigned to the new continuation task.</param>
+        /// <returns>A new continuation <see cref="Task"/>.</returns>
+        /// <remarks>
+        /// The returned <see cref="Task"/> will not be scheduled for execution until the current task has
+        /// completed, whether it completes due to running to completion successfully, faulting due to an
+        /// unhandled exception, or exiting out early due to being canceled.
+        /// </remarks>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="continuationAction"/> argument is null.
+        /// </exception>
+        /// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
+        /// has already been disposed.
+        /// </exception>
+        public Task ContinueWith(Action<Task, object> continuationAction, object state, CancellationToken cancellationToken)
+        {
+            return ContinueWith(continuationAction, state, TaskScheduler.Current, cancellationToken, TaskContinuationOptions.None);
+        }
+
+        /// <summary>
+        /// Creates a continuation that executes when the target <see cref="Task"/> completes.
+        /// </summary>
+        /// <param name="continuationAction">
+        /// An action to run when the <see cref="Task"/> completes.  When run, the delegate will be
+        /// passed the completed task and the caller-supplied state object as arguments.
+        /// </param>
+        /// <param name="state">An object representing data to be used by the continuation action.</param>
+        /// <param name="scheduler">
+        /// The <see cref="TaskScheduler"/> to associate with the continuation task and to use for its execution.
+        /// </param>
+        /// <returns>A new continuation <see cref="Task"/>.</returns>
+        /// <remarks>
+        /// The returned <see cref="Task"/> will not be scheduled for execution until the current task has
+        /// completed, whether it completes due to running to completion successfully, faulting due to an
+        /// unhandled exception, or exiting out early due to being canceled.
+        /// </remarks>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="continuationAction"/> argument is null.
+        /// </exception>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="scheduler"/> argument is null.
+        /// </exception>
+        public Task ContinueWith(Action<Task, object> continuationAction, object state, TaskScheduler scheduler)
+        {
+            return ContinueWith(continuationAction, state, scheduler, default, TaskContinuationOptions.None);
+        }
+
+        /// <summary>
+        /// Creates a continuation that executes when the target <see cref="Task"/> completes.
+        /// </summary>
+        /// <param name="continuationAction">
+        /// An action to run when the <see cref="Task"/> completes. When run, the delegate will be
+        /// passed the completed task and the caller-supplied state object as arguments.
+        /// </param>
+        /// <param name="state">An object representing data to be used by the continuation action.</param>
+        /// <param name="continuationOptions">
+        /// Options for when the continuation is scheduled and how it behaves. This includes criteria, such
+        /// as <see
+        /// cref="System.Threading.Tasks.TaskContinuationOptions.OnlyOnCanceled">OnlyOnCanceled</see>, as
+        /// well as execution options, such as <see
+        /// cref="System.Threading.Tasks.TaskContinuationOptions.ExecuteSynchronously">ExecuteSynchronously</see>.
+        /// </param>
+        /// <returns>A new continuation <see cref="Task"/>.</returns>
+        /// <remarks>
+        /// The returned <see cref="Task"/> will not be scheduled for execution until the current task has
+        /// completed. If the continuation criteria specified through the <paramref
+        /// name="continuationOptions"/> parameter are not met, the continuation task will be canceled
+        /// instead of scheduled.
+        /// </remarks>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="continuationAction"/> argument is null.
+        /// </exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">
+        /// The <paramref name="continuationOptions"/> argument specifies an invalid value for <see
+        /// cref="T:System.Threading.Tasks.TaskContinuationOptions">TaskContinuationOptions</see>.
+        /// </exception>
+        public Task ContinueWith(Action<Task, object> continuationAction, object state, TaskContinuationOptions continuationOptions)
+        {
+            return ContinueWith(continuationAction, state, TaskScheduler.Current, default, continuationOptions);
+        }
+
+        /// <summary>
+        /// Creates a continuation that executes when the target <see cref="Task"/> completes.
+        /// </summary>
+        /// <param name="continuationAction">
+        /// An action to run when the <see cref="Task"/> completes. When run, the delegate will be
+        /// passed the completed task and the caller-supplied state object as arguments.
+        /// </param>
+        /// <param name="state">An object representing data to be used by the continuation action.</param>
+        /// <param name="continuationOptions">
+        /// Options for when the continuation is scheduled and how it behaves. This includes criteria, such
+        /// as <see
+        /// cref="System.Threading.Tasks.TaskContinuationOptions.OnlyOnCanceled">OnlyOnCanceled</see>, as
+        /// well as execution options, such as <see
+        /// cref="System.Threading.Tasks.TaskContinuationOptions.ExecuteSynchronously">ExecuteSynchronously</see>.
+        /// </param>
+        /// <param name="cancellationToken">The <see cref="CancellationToken"/> that will be assigned to the new continuation task.</param>
+        /// <param name="scheduler">
+        /// The <see cref="TaskScheduler"/> to associate with the continuation task and to use for its
+        /// execution.
+        /// </param>
+        /// <returns>A new continuation <see cref="Task"/>.</returns>
+        /// <remarks>
+        /// The returned <see cref="Task"/> will not be scheduled for execution until the current task has
+        /// completed. If the criteria specified through the <paramref name="continuationOptions"/> parameter
+        /// are not met, the continuation task will be canceled instead of scheduled.
+        /// </remarks>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="continuationAction"/> argument is null.
+        /// </exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">
+        /// The <paramref name="continuationOptions"/> argument specifies an invalid value for <see
+        /// cref="T:System.Threading.Tasks.TaskContinuationOptions">TaskContinuationOptions</see>.
+        /// </exception>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="scheduler"/> argument is null.
+        /// </exception>
+        /// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
+        /// has already been disposed.
+        /// </exception>
+        public Task ContinueWith(Action<Task, object> continuationAction, object state, CancellationToken cancellationToken,
+                                 TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
+        {
+            return ContinueWith(continuationAction, state, scheduler, cancellationToken, continuationOptions);
+        }
+
+        // Same as the above overload, just with a stack mark parameter.
+        private Task ContinueWith(Action<Task, object> continuationAction, object state, TaskScheduler scheduler,
+            CancellationToken cancellationToken, TaskContinuationOptions continuationOptions)
+        {
+            // Throw on continuation with null action
+            if (continuationAction == null)
+            {
+                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationAction);
+            }
+
+            // Throw on continuation with null TaskScheduler
+            if (scheduler == null)
+            {
+                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler);
+            }
+
+            TaskCreationOptions creationOptions;
+            InternalTaskOptions internalOptions;
+            CreationOptionsFromContinuationOptions(continuationOptions, out creationOptions, out internalOptions);
+
+            Task continuationTask = new ContinuationTaskFromTask(
+                this, continuationAction, state,
+                creationOptions, internalOptions
+            );
+
+            // Register the continuation.  If synchronous execution is requested, this may
+            // actually invoke the continuation before returning.
+            ContinueWithCore(continuationTask, scheduler, cancellationToken, continuationOptions);
+
+            return continuationTask;
+        }
+
+        #endregion
+
+        #region Func<Task, TResult> continuation
+
+        /// <summary>
+        /// Creates a continuation that executes when the target <see cref="Task"/> completes.
+        /// </summary>
+        /// <typeparam name="TResult">
+        /// The type of the result produced by the continuation.
+        /// </typeparam>
+        /// <param name="continuationFunction">
+        /// A function to run when the <see cref="Task"/> completes. When run, the delegate will be
+        /// passed the completed task as an argument.
+        /// </param>
+        /// <returns>A new continuation <see cref="Task{TResult}"/>.</returns>
+        /// <remarks>
+        /// The returned <see cref="Task{TResult}"/> will not be scheduled for execution until the current task has
+        /// completed, whether it completes due to running to completion successfully, faulting due to an
+        /// unhandled exception, or exiting out early due to being canceled.
+        /// </remarks>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="continuationFunction"/> argument is null.
+        /// </exception>
+        public Task<TResult> ContinueWith<TResult>(Func<Task, TResult> continuationFunction)
+        {
+            return ContinueWith<TResult>(continuationFunction, TaskScheduler.Current, default,
+                TaskContinuationOptions.None);
+        }
+
+
+        /// <summary>
+        /// Creates a continuation that executes when the target <see cref="Task"/> completes.
+        /// </summary>
+        /// <typeparam name="TResult">
+        /// The type of the result produced by the continuation.
+        /// </typeparam>
+        /// <param name="continuationFunction">
+        /// A function to run when the <see cref="Task"/> completes. When run, the delegate will be
+        /// passed the completed task as an argument.
+        /// </param>
+        /// <param name="cancellationToken">The <see cref="CancellationToken"/> that will be assigned to the new continuation task.</param>
+        /// <returns>A new continuation <see cref="Task{TResult}"/>.</returns>
+        /// <remarks>
+        /// The returned <see cref="Task{TResult}"/> will not be scheduled for execution until the current task has
+        /// completed, whether it completes due to running to completion successfully, faulting due to an
+        /// unhandled exception, or exiting out early due to being canceled.
+        /// </remarks>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="continuationFunction"/> argument is null.
+        /// </exception>
+        /// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
+        /// has already been disposed.
+        /// </exception>
+        public Task<TResult> ContinueWith<TResult>(Func<Task, TResult> continuationFunction, CancellationToken cancellationToken)
+        {
+            return ContinueWith<TResult>(continuationFunction, TaskScheduler.Current, cancellationToken, TaskContinuationOptions.None);
+        }
+
+        /// <summary>
+        /// Creates a continuation that executes when the target <see cref="Task"/> completes.
+        /// </summary>
+        /// <typeparam name="TResult">
+        /// The type of the result produced by the continuation.
+        /// </typeparam>
+        /// <param name="continuationFunction">
+        /// A function to run when the <see cref="Task"/> completes.  When run, the delegate will be
+        /// passed the completed task as an argument.
+        /// </param>
+        /// <param name="scheduler">
+        /// The <see cref="TaskScheduler"/> to associate with the continuation task and to use for its execution.
+        /// </param>
+        /// <returns>A new continuation <see cref="Task{TResult}"/>.</returns>
+        /// <remarks>
+        /// The returned <see cref="Task{TResult}"/> will not be scheduled for execution until the current task has
+        /// completed, whether it completes due to running to completion successfully, faulting due to an
+        /// unhandled exception, or exiting out early due to being canceled.
+        /// </remarks>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="continuationFunction"/> argument is null.
+        /// </exception>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="scheduler"/> argument is null.
+        /// </exception>
+        public Task<TResult> ContinueWith<TResult>(Func<Task, TResult> continuationFunction, TaskScheduler scheduler)
+        {
+            return ContinueWith<TResult>(continuationFunction, scheduler, default, TaskContinuationOptions.None);
+        }
+
+        /// <summary>
+        /// Creates a continuation that executes when the target <see cref="Task"/> completes.
+        /// </summary>
+        /// <typeparam name="TResult">
+        /// The type of the result produced by the continuation.
+        /// </typeparam>
+        /// <param name="continuationFunction">
+        /// A function to run when the <see cref="Task"/> completes. When run, the delegate will be
+        /// passed the completed task as an argument.
+        /// </param>
+        /// <param name="continuationOptions">
+        /// Options for when the continuation is scheduled and how it behaves. This includes criteria, such
+        /// as <see
+        /// cref="System.Threading.Tasks.TaskContinuationOptions.OnlyOnCanceled">OnlyOnCanceled</see>, as
+        /// well as execution options, such as <see
+        /// cref="System.Threading.Tasks.TaskContinuationOptions.ExecuteSynchronously">ExecuteSynchronously</see>.
+        /// </param>
+        /// <returns>A new continuation <see cref="Task{TResult}"/>.</returns>
+        /// <remarks>
+        /// The returned <see cref="Task{TResult}"/> will not be scheduled for execution until the current task has
+        /// completed. If the continuation criteria specified through the <paramref
+        /// name="continuationOptions"/> parameter are not met, the continuation task will be canceled
+        /// instead of scheduled.
+        /// </remarks>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="continuationFunction"/> argument is null.
+        /// </exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">
+        /// The <paramref name="continuationOptions"/> argument specifies an invalid value for <see
+        /// cref="T:System.Threading.Tasks.TaskContinuationOptions">TaskContinuationOptions</see>.
+        /// </exception>
+        public Task<TResult> ContinueWith<TResult>(Func<Task, TResult> continuationFunction, TaskContinuationOptions continuationOptions)
+        {
+            return ContinueWith<TResult>(continuationFunction, TaskScheduler.Current, default, continuationOptions);
+        }
+
+        /// <summary>
+        /// Creates a continuation that executes when the target <see cref="Task"/> completes.
+        /// </summary>
+        /// <typeparam name="TResult">
+        /// The type of the result produced by the continuation.
+        /// </typeparam>
+        /// <param name="continuationFunction">
+        /// A function to run when the <see cref="Task"/> completes. When run, the delegate will be
+        /// passed the completed task as an argument.
+        /// </param>
+        /// <param name="cancellationToken">The <see cref="CancellationToken"/> that will be assigned to the new continuation task.</param>
+        /// <param name="continuationOptions">
+        /// Options for when the continuation is scheduled and how it behaves. This includes criteria, such
+        /// as <see
+        /// cref="System.Threading.Tasks.TaskContinuationOptions.OnlyOnCanceled">OnlyOnCanceled</see>, as
+        /// well as execution options, such as <see
+        /// cref="System.Threading.Tasks.TaskContinuationOptions.ExecuteSynchronously">ExecuteSynchronously</see>.
+        /// </param>
+        /// <param name="scheduler">
+        /// The <see cref="TaskScheduler"/> to associate with the continuation task and to use for its
+        /// execution.
+        /// </param>
+        /// <returns>A new continuation <see cref="Task{TResult}"/>.</returns>
+        /// <remarks>
+        /// The returned <see cref="Task{TResult}"/> will not be scheduled for execution until the current task has
+        /// completed. If the criteria specified through the <paramref name="continuationOptions"/> parameter
+        /// are not met, the continuation task will be canceled instead of scheduled.
+        /// </remarks>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="continuationFunction"/> argument is null.
+        /// </exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">
+        /// The <paramref name="continuationOptions"/> argument specifies an invalid value for <see
+        /// cref="T:System.Threading.Tasks.TaskContinuationOptions">TaskContinuationOptions</see>.
+        /// </exception>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="scheduler"/> argument is null.
+        /// </exception>
+        /// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
+        /// has already been disposed.
+        /// </exception>
+        public Task<TResult> ContinueWith<TResult>(Func<Task, TResult> continuationFunction, CancellationToken cancellationToken,
+                                                   TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
+        {
+            return ContinueWith<TResult>(continuationFunction, scheduler, cancellationToken, continuationOptions);
+        }
+
+        // Same as the above overload, just with a stack mark parameter.
+        private Task<TResult> ContinueWith<TResult>(Func<Task, TResult> continuationFunction, TaskScheduler scheduler,
+            CancellationToken cancellationToken, TaskContinuationOptions continuationOptions)
+        {
+            // Throw on continuation with null function
+            if (continuationFunction == null)
+            {
+                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction);
+            }
+
+            // Throw on continuation with null task scheduler
+            if (scheduler == null)
+            {
+                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler);
+            }
+
+            TaskCreationOptions creationOptions;
+            InternalTaskOptions internalOptions;
+            CreationOptionsFromContinuationOptions(continuationOptions, out creationOptions, out internalOptions);
+
+            Task<TResult> continuationTask = new ContinuationResultTaskFromTask<TResult>(
+                this, continuationFunction, null,
+                creationOptions, internalOptions
+            );
+
+            // Register the continuation.  If synchronous execution is requested, this may
+            // actually invoke the continuation before returning.
+            ContinueWithCore(continuationTask, scheduler, cancellationToken, continuationOptions);
+
+            return continuationTask;
+        }
+        #endregion
+
+        #region Func<Task, Object, TResult> continuation
+
+        /// <summary>
+        /// Creates a continuation that executes when the target <see cref="Task"/> completes.
+        /// </summary>
+        /// <typeparam name="TResult">
+        /// The type of the result produced by the continuation.
+        /// </typeparam>
+        /// <param name="continuationFunction">
+        /// A function to run when the <see cref="Task"/> completes. When run, the delegate will be
+        /// passed the completed task and the caller-supplied state object as arguments.
+        /// </param>
+        /// <param name="state">An object representing data to be used by the continuation function.</param>
+        /// <returns>A new continuation <see cref="Task{TResult}"/>.</returns>
+        /// <remarks>
+        /// The returned <see cref="Task{TResult}"/> will not be scheduled for execution until the current task has
+        /// completed, whether it completes due to running to completion successfully, faulting due to an
+        /// unhandled exception, or exiting out early due to being canceled.
+        /// </remarks>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="continuationFunction"/> argument is null.
+        /// </exception>
+        public Task<TResult> ContinueWith<TResult>(Func<Task, object, TResult> continuationFunction, object state)
+        {
+            return ContinueWith<TResult>(continuationFunction, state, TaskScheduler.Current, default,
+                TaskContinuationOptions.None);
+        }
+
+
+        /// <summary>
+        /// Creates a continuation that executes when the target <see cref="Task"/> completes.
+        /// </summary>
+        /// <typeparam name="TResult">
+        /// The type of the result produced by the continuation.
+        /// </typeparam>
+        /// <param name="continuationFunction">
+        /// A function to run when the <see cref="Task"/> completes. When run, the delegate will be
+        /// passed the completed task and the caller-supplied state object as arguments.
+        /// </param>
+        /// <param name="state">An object representing data to be used by the continuation function.</param>
+        /// <param name="cancellationToken">The <see cref="CancellationToken"/> that will be assigned to the new continuation task.</param>
+        /// <returns>A new continuation <see cref="Task{TResult}"/>.</returns>
+        /// <remarks>
+        /// The returned <see cref="Task{TResult}"/> will not be scheduled for execution until the current task has
+        /// completed, whether it completes due to running to completion successfully, faulting due to an
+        /// unhandled exception, or exiting out early due to being canceled.
+        /// </remarks>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="continuationFunction"/> argument is null.
+        /// </exception>
+        /// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
+        /// has already been disposed.
+        /// </exception>
+        public Task<TResult> ContinueWith<TResult>(Func<Task, object, TResult> continuationFunction, object state, CancellationToken cancellationToken)
+        {
+            return ContinueWith<TResult>(continuationFunction, state, TaskScheduler.Current, cancellationToken, TaskContinuationOptions.None);
+        }
+
+        /// <summary>
+        /// Creates a continuation that executes when the target <see cref="Task"/> completes.
+        /// </summary>
+        /// <typeparam name="TResult">
+        /// The type of the result produced by the continuation.
+        /// </typeparam>
+        /// <param name="continuationFunction">
+        /// A function to run when the <see cref="Task"/> completes.  When run, the delegate will be
+        /// passed the completed task and the caller-supplied state object as arguments.
+        /// </param>
+        /// <param name="state">An object representing data to be used by the continuation function.</param>
+        /// <param name="scheduler">
+        /// The <see cref="TaskScheduler"/> to associate with the continuation task and to use for its execution.
+        /// </param>
+        /// <returns>A new continuation <see cref="Task{TResult}"/>.</returns>
+        /// <remarks>
+        /// The returned <see cref="Task{TResult}"/> will not be scheduled for execution until the current task has
+        /// completed, whether it completes due to running to completion successfully, faulting due to an
+        /// unhandled exception, or exiting out early due to being canceled.
+        /// </remarks>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="continuationFunction"/> argument is null.
+        /// </exception>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="scheduler"/> argument is null.
+        /// </exception>
+        public Task<TResult> ContinueWith<TResult>(Func<Task, object, TResult> continuationFunction, object state, TaskScheduler scheduler)
+        {
+            return ContinueWith<TResult>(continuationFunction, state, scheduler, default, TaskContinuationOptions.None);
+        }
+
+        /// <summary>
+        /// Creates a continuation that executes when the target <see cref="Task"/> completes.
+        /// </summary>
+        /// <typeparam name="TResult">
+        /// The type of the result produced by the continuation.
+        /// </typeparam>
+        /// <param name="continuationFunction">
+        /// A function to run when the <see cref="Task"/> completes. When run, the delegate will be
+        /// passed the completed task and the caller-supplied state object as arguments.
+        /// </param>
+        /// <param name="state">An object representing data to be used by the continuation function.</param>
+        /// <param name="continuationOptions">
+        /// Options for when the continuation is scheduled and how it behaves. This includes criteria, such
+        /// as <see
+        /// cref="System.Threading.Tasks.TaskContinuationOptions.OnlyOnCanceled">OnlyOnCanceled</see>, as
+        /// well as execution options, such as <see
+        /// cref="System.Threading.Tasks.TaskContinuationOptions.ExecuteSynchronously">ExecuteSynchronously</see>.
+        /// </param>
+        /// <returns>A new continuation <see cref="Task{TResult}"/>.</returns>
+        /// <remarks>
+        /// The returned <see cref="Task{TResult}"/> will not be scheduled for execution until the current task has
+        /// completed. If the continuation criteria specified through the <paramref
+        /// name="continuationOptions"/> parameter are not met, the continuation task will be canceled
+        /// instead of scheduled.
+        /// </remarks>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="continuationFunction"/> argument is null.
+        /// </exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">
+        /// The <paramref name="continuationOptions"/> argument specifies an invalid value for <see
+        /// cref="T:System.Threading.Tasks.TaskContinuationOptions">TaskContinuationOptions</see>.
+        /// </exception>
+        public Task<TResult> ContinueWith<TResult>(Func<Task, object, TResult> continuationFunction, object state, TaskContinuationOptions continuationOptions)
+        {
+            return ContinueWith<TResult>(continuationFunction, state, TaskScheduler.Current, default, continuationOptions);
+        }
+
+        /// <summary>
+        /// Creates a continuation that executes when the target <see cref="Task"/> completes.
+        /// </summary>
+        /// <typeparam name="TResult">
+        /// The type of the result produced by the continuation.
+        /// </typeparam>
+        /// <param name="continuationFunction">
+        /// A function to run when the <see cref="Task"/> completes. When run, the delegate will be
+        /// passed the completed task and the caller-supplied state object as arguments.
+        /// </param>
+        /// <param name="state">An object representing data to be used by the continuation function.</param>
+        /// <param name="cancellationToken">The <see cref="CancellationToken"/> that will be assigned to the new continuation task.</param>
+        /// <param name="continuationOptions">
+        /// Options for when the continuation is scheduled and how it behaves. This includes criteria, such
+        /// as <see
+        /// cref="System.Threading.Tasks.TaskContinuationOptions.OnlyOnCanceled">OnlyOnCanceled</see>, as
+        /// well as execution options, such as <see
+        /// cref="System.Threading.Tasks.TaskContinuationOptions.ExecuteSynchronously">ExecuteSynchronously</see>.
+        /// </param>
+        /// <param name="scheduler">
+        /// The <see cref="TaskScheduler"/> to associate with the continuation task and to use for its
+        /// execution.
+        /// </param>
+        /// <returns>A new continuation <see cref="Task{TResult}"/>.</returns>
+        /// <remarks>
+        /// The returned <see cref="Task{TResult}"/> will not be scheduled for execution until the current task has
+        /// completed. If the criteria specified through the <paramref name="continuationOptions"/> parameter
+        /// are not met, the continuation task will be canceled instead of scheduled.
+        /// </remarks>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="continuationFunction"/> argument is null.
+        /// </exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">
+        /// The <paramref name="continuationOptions"/> argument specifies an invalid value for <see
+        /// cref="T:System.Threading.Tasks.TaskContinuationOptions">TaskContinuationOptions</see>.
+        /// </exception>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="scheduler"/> argument is null.
+        /// </exception>
+        /// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
+        /// has already been disposed.
+        /// </exception>
+        public Task<TResult> ContinueWith<TResult>(Func<Task, object, TResult> continuationFunction, object state, CancellationToken cancellationToken,
+                                                   TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
+        {
+            return ContinueWith<TResult>(continuationFunction, state, scheduler, cancellationToken, continuationOptions);
+        }
+
+        // Same as the above overload, just with a stack mark parameter.
+        private Task<TResult> ContinueWith<TResult>(Func<Task, object, TResult> continuationFunction, object state, TaskScheduler scheduler,
+            CancellationToken cancellationToken, TaskContinuationOptions continuationOptions)
+        {
+            // Throw on continuation with null function
+            if (continuationFunction == null)
+            {
+                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction);
+            }
+
+            // Throw on continuation with null task scheduler
+            if (scheduler == null)
+            {
+                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler);
+            }
+
+            TaskCreationOptions creationOptions;
+            InternalTaskOptions internalOptions;
+            CreationOptionsFromContinuationOptions(continuationOptions, out creationOptions, out internalOptions);
+
+            Task<TResult> continuationTask = new ContinuationResultTaskFromTask<TResult>(
+                this, continuationFunction, state,
+                creationOptions, internalOptions
+            );
+
+            // Register the continuation.  If synchronous execution is requested, this may
+            // actually invoke the continuation before returning.
+            ContinueWithCore(continuationTask, scheduler, cancellationToken, continuationOptions);
+
+            return continuationTask;
+        }
+        #endregion
+
+        /// <summary>
+        /// Converts TaskContinuationOptions to TaskCreationOptions, and also does
+        /// some validity checking along the way.
+        /// </summary>
+        /// <param name="continuationOptions">Incoming TaskContinuationOptions</param>
+        /// <param name="creationOptions">Outgoing TaskCreationOptions</param>
+        /// <param name="internalOptions">Outgoing InternalTaskOptions</param>
+        internal static void CreationOptionsFromContinuationOptions(
+            TaskContinuationOptions continuationOptions,
+            out TaskCreationOptions creationOptions,
+            out InternalTaskOptions internalOptions)
+        {
+            // This is used a couple of times below
+            const TaskContinuationOptions NotOnAnything =
+                TaskContinuationOptions.NotOnCanceled |
+                TaskContinuationOptions.NotOnFaulted |
+                TaskContinuationOptions.NotOnRanToCompletion;
+
+            const TaskContinuationOptions CreationOptionsMask =
+                TaskContinuationOptions.PreferFairness |
+                TaskContinuationOptions.LongRunning |
+                TaskContinuationOptions.DenyChildAttach |
+                TaskContinuationOptions.HideScheduler |
+                TaskContinuationOptions.AttachedToParent |
+                TaskContinuationOptions.RunContinuationsAsynchronously;
+
+            // Check that LongRunning and ExecuteSynchronously are not specified together
+            const TaskContinuationOptions IllegalMask = TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.LongRunning;
+            if ((continuationOptions & IllegalMask) == IllegalMask)
+            {
+                ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.continuationOptions, ExceptionResource.Task_ContinueWith_ESandLR);
+            }
+
+            // Check that no illegal options were specified
+            if ((continuationOptions &
+                ~(CreationOptionsMask | NotOnAnything |
+                    TaskContinuationOptions.LazyCancellation | TaskContinuationOptions.ExecuteSynchronously)) != 0)
+            {
+                ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.continuationOptions);
+            }
+
+            // Check that we didn't specify "not on anything"
+            if ((continuationOptions & NotOnAnything) == NotOnAnything)
+            {
+                ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.continuationOptions, ExceptionResource.Task_ContinueWith_NotOnAnything);
+            }
+
+            // This passes over all but LazyCancellation, which has no representation in TaskCreationOptions
+            creationOptions = (TaskCreationOptions)(continuationOptions & CreationOptionsMask);
+
+            // internalOptions has at least ContinuationTask and possibly LazyCancellation
+            internalOptions = (continuationOptions & TaskContinuationOptions.LazyCancellation) != 0 ?
+                InternalTaskOptions.ContinuationTask | InternalTaskOptions.LazyCancellation :
+                InternalTaskOptions.ContinuationTask;
+        }
+
+
+        /// <summary>
+        /// Registers the continuation and possibly runs it (if the task is already finished).
+        /// </summary>
+        /// <param name="continuationTask">The continuation task itself.</param>
+        /// <param name="scheduler">TaskScheduler with which to associate continuation task.</param>
+        /// <param name="options">Restrictions on when the continuation becomes active.</param>
+        internal void ContinueWithCore(Task continuationTask,
+                                       TaskScheduler scheduler,
+                                       CancellationToken cancellationToken,
+                                       TaskContinuationOptions options)
+        {
+            Debug.Assert(continuationTask != null, "Task.ContinueWithCore(): null continuationTask");
+            Debug.Assert(scheduler != null, "Task.ContinueWithCore(): null scheduler");
+            Debug.Assert(!continuationTask.IsCompleted, "Did not expect continuationTask to be completed");
+
+            // Create a TaskContinuation
+            TaskContinuation continuation = new StandardTaskContinuation(continuationTask, options, scheduler);
+
+            // If cancellationToken is cancellable, then assign it.  
+            if (cancellationToken.CanBeCanceled)
+            {
+                if (IsCompleted || cancellationToken.IsCancellationRequested)
+                {
+                    // If the antecedent has completed, then we will not be queuing up
+                    // the continuation in the antecedent's continuation list.  Likewise,
+                    // if the cancellationToken has been canceled, continuationTask will
+                    // be completed in the AssignCancellationToken call below, and there
+                    // is no need to queue the continuation to the antecedent's continuation
+                    // list.  In either of these two cases, we will pass "null" for the antecedent,
+                    // meaning "the cancellation callback should not attempt to remove the
+                    // continuation from its antecedent's continuation list".
+                    continuationTask.AssignCancellationToken(cancellationToken, null, null);
+                }
+                else
+                {
+                    // The antecedent is not yet complete, so there is a pretty good chance
+                    // that the continuation will be queued up in the antecedent.  Assign the
+                    // cancellation token with information about the antecedent, so that the
+                    // continuation can be dequeued upon the signalling of the token.
+                    //
+                    // It's possible that the antecedent completes before the call to AddTaskContinuation,
+                    // and that is a benign race condition.  It just means that the cancellation will result in
+                    // a futile search of the antecedent's continuation list.
+                    continuationTask.AssignCancellationToken(cancellationToken, this, continuation);
+                }
+            }
+
+            // In the case of a pre-canceled token, continuationTask will have been completed
+            // in a Canceled state by now.  If such is the case, there is no need to go through
+            // the motions of queuing up the continuation for eventual execution.
+            if (!continuationTask.IsCompleted)
+            {
+                // Attempt to enqueue the continuation
+                bool continuationQueued = AddTaskContinuation(continuation, addBeforeOthers: false);
+
+                // If the continuation was not queued (because the task completed), then run it now.
+                if (!continuationQueued) continuation.Run(this, canInlineContinuationTask: true);
+            }
+        }
+        #endregion
+
+        // Adds a lightweight completion action to a task.  This is similar to a continuation
+        // task except that it is stored as an action, and thus does not require the allocation/
+        // execution resources of a continuation task.
+        //
+        // Used internally by ContinueWhenAll() and ContinueWhenAny().
+        internal void AddCompletionAction(ITaskCompletionAction action)
+        {
+            AddCompletionAction(action, addBeforeOthers: false);
+        }
+
+        private void AddCompletionAction(ITaskCompletionAction action, bool addBeforeOthers)
+        {
+            if (!AddTaskContinuation(action, addBeforeOthers))
+                action.Invoke(this); // run the action directly if we failed to queue the continuation (i.e., the task completed)
+        }
+
+        // Support method for AddTaskContinuation that takes care of multi-continuation logic.
+        // Returns true if and only if the continuation was successfully queued.
+        // THIS METHOD ASSUMES THAT m_continuationObject IS NOT NULL.  That case was taken
+        // care of in the calling method, AddTaskContinuation().
+        private bool AddTaskContinuationComplex(object tc, bool addBeforeOthers)
+        {
+            Debug.Assert(tc != null, "Expected non-null tc object in AddTaskContinuationComplex");
+
+            object oldValue = m_continuationObject;
+
+            // Logic for the case where we were previously storing a single continuation
+            if ((oldValue != s_taskCompletionSentinel) && (!(oldValue is List<object>)))
+            {
+                // Construct a new TaskContinuation list
+                List<object> newList = new List<object>();
+
+                // Add in the old single value
+                newList.Add(oldValue);
+
+                // Now CAS in the new list
+                Interlocked.CompareExchange(ref m_continuationObject, newList, oldValue);
+
+                // We might be racing against another thread converting the single into
+                // a list, or we might be racing against task completion, so resample "list"
+                // below.
+            }
+
+            // m_continuationObject is guaranteed at this point to be either a List or
+            // s_taskCompletionSentinel.
+            List<object> list = m_continuationObject as List<object>;
+            Debug.Assert((list != null) || (m_continuationObject == s_taskCompletionSentinel),
+                "Expected m_continuationObject to be list or sentinel");
+
+            // If list is null, it can only mean that s_taskCompletionSentinel has been exchanged
+            // into m_continuationObject.  Thus, the task has completed and we should return false
+            // from this method, as we will not be queuing up the continuation.
+            if (list != null)
+            {
+                lock (list)
+                {
+                    // It is possible for the task to complete right after we snap the copy of
+                    // the list.  If so, then fall through and return false without queuing the
+                    // continuation.
+                    if (m_continuationObject != s_taskCompletionSentinel)
+                    {
+                        // Before growing the list we remove possible null entries that are the
+                        // result from RemoveContinuations()
+                        if (list.Count == list.Capacity)
+                        {
+                            list.RemoveAll(s_IsTaskContinuationNullPredicate);
+                        }
+
+                        if (addBeforeOthers)
+                            list.Insert(0, tc);
+                        else
+                            list.Add(tc);
+
+                        return true; // continuation successfully queued, so return true.
+                    }
+                }
+            }
+
+            // We didn't succeed in queuing the continuation, so return false.
+            return false;
+        }
+
+        // Record a continuation task or action.
+        // Return true if and only if we successfully queued a continuation.
+        private bool AddTaskContinuation(object tc, bool addBeforeOthers)
+        {
+            Debug.Assert(tc != null);
+
+            // Make sure that, if someone calls ContinueWith() right after waiting for the predecessor to complete,
+            // we don't queue up a continuation.
+            if (IsCompleted) return false;
+
+            // Try to just jam tc into m_continuationObject
+            if ((m_continuationObject != null) || (Interlocked.CompareExchange(ref m_continuationObject, tc, null) != null))
+            {
+                // If we get here, it means that we failed to CAS tc into m_continuationObject.
+                // Therefore, we must go the more complicated route.
+                return AddTaskContinuationComplex(tc, addBeforeOthers);
+            }
+            else return true;
+        }
+
+        // Removes a continuation task from m_continuations
+        internal void RemoveContinuation(object continuationObject) // could be TaskContinuation or Action<Task>
+        {
+            // We need to snap a local reference to m_continuations since reading a volatile object is more costly.
+            // Also to prevent the value to be changed as result of a race condition with another method.
+            object continuationsLocalRef = m_continuationObject;
+
+            // Task is completed. Nothing to do here.
+            if (continuationsLocalRef == s_taskCompletionSentinel) return;
+
+            List<object> continuationsLocalListRef = continuationsLocalRef as List<object>;
+
+            if (continuationsLocalListRef == null)
+            {
+                // This is not a list. If we have a single object (the one we want to remove) we try to replace it with an empty list.
+                // Note we cannot go back to a null state, since it will mess up the AddTaskContinuation logic.
+                if (Interlocked.CompareExchange(ref m_continuationObject, new List<object>(), continuationObject) != continuationObject)
+                {
+                    // If we fail it means that either AddContinuationComplex won the race condition and m_continuationObject is now a List
+                    // that contains the element we want to remove. Or FinishContinuations set the s_taskCompletionSentinel.
+                    // So we should try to get a list one more time
+                    continuationsLocalListRef = m_continuationObject as List<object>;
+                }
+                else
+                {
+                    // Exchange was successful so we can skip the last comparison
+                    return;
+                }
+            }
+
+            // if continuationsLocalRef == null it means s_taskCompletionSentinel has been set already and there is nothing else to do.
+            if (continuationsLocalListRef != null)
+            {
+                lock (continuationsLocalListRef)
+                {
+                    // There is a small chance that this task completed since we took a local snapshot into
+                    // continuationsLocalRef.  In that case, just return; we don't want to be manipulating the
+                    // continuation list as it is being processed.
+                    if (m_continuationObject == s_taskCompletionSentinel) return;
+
+                    // Find continuationObject in the continuation list
+                    int index = continuationsLocalListRef.IndexOf(continuationObject);
+
+                    if (index != -1)
+                    {
+                        // null out that TaskContinuation entry, which will be interpreted as "to be cleaned up"
+                        continuationsLocalListRef[index] = null;
+                    }
+                }
+            }
+        }
+
+        // statically allocated delegate for the RemoveAll expression in RemoveContinuations() and AddContinuationComplex()
+        private readonly static Predicate<object> s_IsTaskContinuationNullPredicate =
+            new Predicate<object>((tc) => { return (tc == null); });
+
+
+        //
+        // Wait methods
+        //
+
+        /// <summary>
+        /// Waits for all of the provided <see cref="Task"/> objects to complete execution.
+        /// </summary>
+        /// <param name="tasks">
+        /// An array of <see cref="Task"/> instances on which to wait.
+        /// </param>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="tasks"/> argument is null.
+        /// </exception>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="tasks"/> argument contains a null element.
+        /// </exception>
+        /// <exception cref="T:System.AggregateException">
+        /// At least one of the <see cref="Task"/> instances was canceled -or- an exception was thrown during
+        /// the execution of at least one of the <see cref="Task"/> instances.
+        /// </exception>
+        [MethodImpl(MethodImplOptions.NoOptimization)]  // this is needed for the parallel debugger
+        public static void WaitAll(params Task[] tasks)
+        {
+#if DEBUG
+            bool waitResult =
+#endif
+            WaitAllCore(tasks, Timeout.Infinite, default);
+
+#if DEBUG
+            Debug.Assert(waitResult, "expected wait to succeed");
+#endif
+        }
+
+        /// <summary>
+        /// Waits for all of the provided <see cref="Task"/> objects to complete execution.
+        /// </summary>
+        /// <returns>
+        /// true if all of the <see cref="Task"/> instances completed execution within the allotted time;
+        /// otherwise, false.
+        /// </returns>
+        /// <param name="tasks">
+        /// An array of <see cref="Task"/> instances on which to wait.
+        /// </param>
+        /// <param name="timeout">
+        /// A <see cref="System.TimeSpan"/> that represents the number of milliseconds to wait, or a <see
+        /// cref="System.TimeSpan"/> that represents -1 milliseconds to wait indefinitely.
+        /// </param>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="tasks"/> argument is null.
+        /// </exception>
+        /// <exception cref="T:System.ArgumentException">
+        /// The <paramref name="tasks"/> argument contains a null element.
+        /// </exception>
+        /// <exception cref="T:System.AggregateException">
+        /// At least one of the <see cref="Task"/> instances was canceled -or- an exception was thrown during
+        /// the execution of at least one of the <see cref="Task"/> instances.
+        /// </exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">
+        /// <paramref name="timeout"/> is a negative number other than -1 milliseconds, which represents an
+        /// infinite time-out -or- timeout is greater than
+        /// <see cref="System.Int32.MaxValue"/>.
+        /// </exception>
+        [MethodImpl(MethodImplOptions.NoOptimization)]  // this is needed for the parallel debugger
+        public static bool WaitAll(Task[] tasks, TimeSpan timeout)
+        {
+            long totalMilliseconds = (long)timeout.TotalMilliseconds;
+            if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue)
+            {
+                ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.timeout);
+            }
+
+            return WaitAllCore(tasks, (int)totalMilliseconds, default);
+        }
+
+        /// <summary>
+        /// Waits for all of the provided <see cref="Task"/> objects to complete execution.
+        /// </summary>
+        /// <returns>
+        /// true if all of the <see cref="Task"/> instances completed execution within the allotted time;
+        /// otherwise, false.
+        /// </returns>
+        /// <param name="millisecondsTimeout">
+        /// The number of milliseconds to wait, or <see cref="System.Threading.Timeout.Infinite"/> (-1) to
+        /// wait indefinitely.</param>
+        /// <param name="tasks">An array of <see cref="Task"/> instances on which to wait.
+        /// </param>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="tasks"/> argument is null.
+        /// </exception>
+        /// <exception cref="T:System.ArgumentException">
+        /// The <paramref name="tasks"/> argument contains a null element.
+        /// </exception>
+        /// <exception cref="T:System.AggregateException">
+        /// At least one of the <see cref="Task"/> instances was canceled -or- an exception was thrown during
+        /// the execution of at least one of the <see cref="Task"/> instances.
+        /// </exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">
+        /// <paramref name="millisecondsTimeout"/> is a negative number other than -1, which represents an
+        /// infinite time-out.
+        /// </exception>
+        [MethodImpl(MethodImplOptions.NoOptimization)]  // this is needed for the parallel debugger
+        public static bool WaitAll(Task[] tasks, int millisecondsTimeout)
+        {
+            return WaitAllCore(tasks, millisecondsTimeout, default);
+        }
+
+        /// <summary>
+        /// Waits for all of the provided <see cref="Task"/> objects to complete execution.
+        /// </summary>
+        /// <returns>
+        /// true if all of the <see cref="Task"/> instances completed execution within the allotted time;
+        /// otherwise, false.
+        /// </returns>
+        /// <param name="tasks">
+        /// An array of <see cref="Task"/> instances on which to wait.
+        /// </param>
+        /// <param name="cancellationToken">
+        /// A <see cref="CancellationToken"/> to observe while waiting for the tasks to complete.
+        /// </param>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="tasks"/> argument is null.
+        /// </exception>
+        /// <exception cref="T:System.ArgumentException">
+        /// The <paramref name="tasks"/> argument contains a null element.
+        /// </exception>
+        /// <exception cref="T:System.AggregateException">
+        /// At least one of the <see cref="Task"/> instances was canceled -or- an exception was thrown during
+        /// the execution of at least one of the <see cref="Task"/> instances.
+        /// </exception>
+        /// <exception cref="T:System.OperationCanceledException">
+        /// The <paramref name="cancellationToken"/> was canceled.
+        /// </exception>
+        [MethodImpl(MethodImplOptions.NoOptimization)]  // this is needed for the parallel debugger
+        public static void WaitAll(Task[] tasks, CancellationToken cancellationToken)
+        {
+            WaitAllCore(tasks, Timeout.Infinite, cancellationToken);
+        }
+
+        /// <summary>
+        /// Waits for all of the provided <see cref="Task"/> objects to complete execution.
+        /// </summary>
+        /// <returns>
+        /// true if all of the <see cref="Task"/> instances completed execution within the allotted time;
+        /// otherwise, false.
+        /// </returns>
+        /// <param name="tasks">
+        /// An array of <see cref="Task"/> instances on which to wait.
+        /// </param>
+        /// <param name="millisecondsTimeout">
+        /// The number of milliseconds to wait, or <see cref="System.Threading.Timeout.Infinite"/> (-1) to
+        /// wait indefinitely.
+        /// </param>
+        /// <param name="cancellationToken">
+        /// A <see cref="CancellationToken"/> to observe while waiting for the tasks to complete.
+        /// </param>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="tasks"/> argument is null.
+        /// </exception>
+        /// <exception cref="T:System.ArgumentException">
+        /// The <paramref name="tasks"/> argument contains a null element.
+        /// </exception>
+        /// <exception cref="T:System.AggregateException">
+        /// At least one of the <see cref="Task"/> instances was canceled -or- an exception was thrown during
+        /// the execution of at least one of the <see cref="Task"/> instances.
+        /// </exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">
+        /// <paramref name="millisecondsTimeout"/> is a negative number other than -1, which represents an
+        /// infinite time-out.
+        /// </exception>
+        /// <exception cref="T:System.OperationCanceledException">
+        /// The <paramref name="cancellationToken"/> was canceled.
+        /// </exception>
+        [MethodImpl(MethodImplOptions.NoOptimization)]  // this is needed for the parallel debugger
+        public static bool WaitAll(Task[] tasks, int millisecondsTimeout, CancellationToken cancellationToken) =>
+            WaitAllCore(tasks, millisecondsTimeout, cancellationToken);
+
+        // Separated out to allow it to be optimized (caller is marked NoOptimization for VS parallel debugger
+        // to be able to see the method on the stack and inspect arguments).
+        private static bool WaitAllCore(Task[] tasks, int millisecondsTimeout, CancellationToken cancellationToken)
+        {
+            if (tasks == null)
+            {
+                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.tasks);
+            }
+            if (millisecondsTimeout < -1)
+            {
+                ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.millisecondsTimeout);
+            }
+
+            cancellationToken.ThrowIfCancellationRequested(); // early check before we make any allocations
+
+            //
+            // In this WaitAll() implementation we have 2 alternate code paths for a task to be handled:
+            // CODEPATH1: skip an already completed task, CODEPATH2: actually wait on tasks
+            // We make sure that the exception behavior of Task.Wait() is replicated the same for tasks handled in either of these codepaths
+            //
+
+            List<Exception> exceptions = null;
+            List<Task> waitedOnTaskList = null;
+            List<Task> notificationTasks = null;
+
+            // If any of the waited-upon tasks end as Faulted or Canceled, set these to true.
+            bool exceptionSeen = false, cancellationSeen = false;
+
+            bool returnValue = true;
+
+            // Collects incomplete tasks in "waitedOnTaskList"
+            for (int i = tasks.Length - 1; i >= 0; i--)
+            {
+                Task task = tasks[i];
+
+                if (task == null)
+                {
+                    ThrowHelper.ThrowArgumentException(ExceptionResource.Task_WaitMulti_NullTask, ExceptionArgument.tasks);
+                }
+
+                bool taskIsCompleted = task.IsCompleted;
+                if (!taskIsCompleted)
+                {
+                    // try inlining the task only if we have an infinite timeout and an empty cancellation token
+                    if (millisecondsTimeout != Timeout.Infinite || cancellationToken.CanBeCanceled)
+                    {
+                        // We either didn't attempt inline execution because we had a non-infinite timeout or we had a cancellable token.
+                        // In all cases we need to do a full wait on the task (=> add its event into the list.)
+                        AddToList(task, ref waitedOnTaskList, initSize: tasks.Length);
+                    }
+                    else
+                    {
+                        // We are eligible for inlining.  If it doesn't work, we'll do a full wait.
+                        taskIsCompleted = task.WrappedTryRunInline() && task.IsCompleted; // A successful TryRunInline doesn't guarantee completion
+                        if (!taskIsCompleted) AddToList(task, ref waitedOnTaskList, initSize: tasks.Length);
+                    }
+                }
+
+                if (taskIsCompleted)
+                {
+                    if (task.IsFaulted) exceptionSeen = true;
+                    else if (task.IsCanceled) cancellationSeen = true;
+                    if (task.IsWaitNotificationEnabled) AddToList(task, ref notificationTasks, initSize: 1);
+                }
+            }
+
+            if (waitedOnTaskList != null)
+            {
+                // Block waiting for the tasks to complete.
+                returnValue = WaitAllBlockingCore(waitedOnTaskList, millisecondsTimeout, cancellationToken);
+
+                // If the wait didn't time out, ensure exceptions are propagated, and if a debugger is
+                // attached and one of these tasks requires it, that we notify the debugger of a wait completion.
+                if (returnValue)
+                {
+                    // Add any exceptions for this task to the collection, and if it's wait
+                    // notification bit is set, store it to operate on at the end.
+                    foreach (var task in waitedOnTaskList)
+                    {
+                        if (task.IsFaulted) exceptionSeen = true;
+                        else if (task.IsCanceled) cancellationSeen = true;
+                        if (task.IsWaitNotificationEnabled) AddToList(task, ref notificationTasks, initSize: 1);
+                    }
+                }
+
+                // We need to prevent the tasks array from being GC'ed until we come out of the wait.
+                // This is necessary so that the Parallel Debugger can traverse it during the long wait and 
+                // deduce waiter/waitee relationships
+                GC.KeepAlive(tasks);
+            }
+
+            // Now that we're done and about to exit, if the wait completed and if we have 
+            // any tasks with a notification bit set, signal the debugger if any requires it.
+            if (returnValue && notificationTasks != null)
+            {
+                // Loop through each task tha that had its bit set, and notify the debugger
+                // about the first one that requires it.  The debugger will reset the bit
+                // for any tasks we don't notify of as soon as we break, so we only need to notify
+                // for one.
+                foreach (var task in notificationTasks)
+                {
+                    if (task.NotifyDebuggerOfWaitCompletionIfNecessary()) break;
+                }
+            }
+
+            // If one or more threw exceptions, aggregate and throw them.
+            if (returnValue && (exceptionSeen || cancellationSeen))
+            {
+                // If the WaitAll was canceled and tasks were canceled but not faulted, 
+                // prioritize throwing an OCE for canceling the WaitAll over throwing an 
+                // AggregateException for all of the canceled Tasks.  This helps
+                // to bring determinism to an otherwise non-determistic case of using
+                // the same token to cancel both the WaitAll and the Tasks.
+                if (!exceptionSeen) cancellationToken.ThrowIfCancellationRequested();
+
+                // Now gather up and throw all of the exceptions.
+                foreach (var task in tasks) AddExceptionsForCompletedTask(ref exceptions, task);
+                Debug.Assert(exceptions != null, "Should have seen at least one exception");
+                ThrowHelper.ThrowAggregateException(exceptions);
+            }
+
+            return returnValue;
+        }
+
+        /// <summary>Adds an element to the list, initializing the list if it's null.</summary>
+        /// <typeparam name="T">Specifies the type of data stored in the list.</typeparam>
+        /// <param name="item">The item to add.</param>
+        /// <param name="list">The list.</param>
+        /// <param name="initSize">The size to which to initialize the list if the list is null.</param>
+        private static void AddToList<T>(T item, ref List<T> list, int initSize)
+        {
+            if (list == null) list = new List<T>(initSize);
+            list.Add(item);
+        }
+
+        /// <summary>Performs a blocking WaitAll on the vetted list of tasks.</summary>
+        /// <param name="tasks">The tasks, which have already been checked and filtered for completion.</param>
+        /// <param name="millisecondsTimeout">The timeout.</param>
+        /// <param name="cancellationToken">The cancellation token.</param>
+        /// <returns>true if all of the tasks completed; otherwise, false.</returns>
+        private static bool WaitAllBlockingCore(List<Task> tasks, int millisecondsTimeout, CancellationToken cancellationToken)
+        {
+            Debug.Assert(tasks != null, "Expected a non-null list of tasks");
+            Debug.Assert(tasks.Count > 0, "Expected at least one task");
+
+            bool waitCompleted = false;
+            var mres = new SetOnCountdownMres(tasks.Count);
+            try
+            {
+                foreach (var task in tasks)
+                {
+                    task.AddCompletionAction(mres, addBeforeOthers: true);
+                }
+                waitCompleted = mres.Wait(millisecondsTimeout, cancellationToken);
+            }
+            finally
+            {
+                if (!waitCompleted)
+                {
+                    foreach (var task in tasks)
+                    {
+                        if (!task.IsCompleted) task.RemoveContinuation(mres);
+                    }
+                }
+                // It's ok that we don't dispose of the MRES here, as we never
+                // access the MRES' WaitHandle, and thus no finalizable resources
+                // are actually created.  We don't always just Dispose it because
+                // a continuation that's accessing the MRES could still be executing.
+            }
+            return waitCompleted;
+        }
+
+        // A ManualResetEventSlim that will get Set after Invoke is called count times.
+        // This allows us to replace this logic:
+        //      var mres = new ManualResetEventSlim(tasks.Count);
+        //      Action<Task> completionAction = delegate { if(Interlocked.Decrement(ref count) == 0) mres.Set(); };
+        //      foreach(var task in tasks) task.AddCompletionAction(completionAction);
+        // with this logic:
+        //      var mres = new SetOnCountdownMres(tasks.Count);
+        //      foreach(var task in tasks) task.AddCompletionAction(mres);
+        // which saves a couple of allocations.
+        //
+        // Used in WaitAllBlockingCore (above).
+        private sealed class SetOnCountdownMres : ManualResetEventSlim, ITaskCompletionAction
+        {
+            private int _count;
+
+            internal SetOnCountdownMres(int count)
+            {
+                Debug.Assert(count > 0, "Expected count > 0");
+                _count = count;
+            }
+
+            public void Invoke(Task completingTask)
+            {
+                if (Interlocked.Decrement(ref _count) == 0) Set();
+                Debug.Assert(_count >= 0, "Count should never go below 0");
+            }
+
+            public bool InvokeMayRunArbitraryCode { get { return false; } }
+        }
+
+        /// <summary>
+        /// This internal function is only meant to be called by WaitAll()
+        /// If the completed task is canceled or it has other exceptions, here we will add those
+        /// into the passed in exception list (which will be lazily initialized here).
+        /// </summary>
+        internal static void AddExceptionsForCompletedTask(ref List<Exception> exceptions, Task t)
+        {
+            AggregateException ex = t.GetExceptions(true);
+            if (ex != null)
+            {
+                // make sure the task's exception observed status is set appropriately
+                // it's possible that WaitAll was called by the parent of an attached child,
+                // this will make sure it won't throw again in the implicit wait
+                t.UpdateExceptionObservedStatus();
+
+                if (exceptions == null)
+                {
+                    exceptions = new List<Exception>(ex.InnerExceptions.Count);
+                }
+
+                exceptions.AddRange(ex.InnerExceptions);
+            }
+        }
+
+
+        /// <summary>
+        /// Waits for any of the provided <see cref="Task"/> objects to complete execution.
+        /// </summary>
+        /// <param name="tasks">
+        /// An array of <see cref="Task"/> instances on which to wait.
+        /// </param>
+        /// <returns>The index of the completed task in the <paramref name="tasks"/> array argument.</returns>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="tasks"/> argument is null.
+        /// </exception>
+        /// <exception cref="T:System.ArgumentException">
+        /// The <paramref name="tasks"/> argument contains a null element.
+        /// </exception>
+        [MethodImpl(MethodImplOptions.NoOptimization)]  // this is needed for the parallel debugger
+        public static int WaitAny(params Task[] tasks)
+        {
+            int waitResult = WaitAnyCore(tasks, Timeout.Infinite, default);
+            Debug.Assert(tasks.Length == 0 || waitResult != -1, "expected wait to succeed");
+            return waitResult;
+        }
+
+        /// <summary>
+        /// Waits for any of the provided <see cref="Task"/> objects to complete execution.
+        /// </summary>
+        /// <param name="tasks">
+        /// An array of <see cref="Task"/> instances on which to wait.
+        /// </param>
+        /// <param name="timeout">
+        /// A <see cref="System.TimeSpan"/> that represents the number of milliseconds to wait, or a <see
+        /// cref="System.TimeSpan"/> that represents -1 milliseconds to wait indefinitely.
+        /// </param>
+        /// <returns>
+        /// The index of the completed task in the <paramref name="tasks"/> array argument, or -1 if the
+        /// timeout occurred.
+        /// </returns>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="tasks"/> argument is null.
+        /// </exception>
+        /// <exception cref="T:System.ArgumentException">
+        /// The <paramref name="tasks"/> argument contains a null element.
+        /// </exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">
+        /// <paramref name="timeout"/> is a negative number other than -1 milliseconds, which represents an
+        /// infinite time-out -or- timeout is greater than
+        /// <see cref="System.Int32.MaxValue"/>.
+        /// </exception>
+        [MethodImpl(MethodImplOptions.NoOptimization)]  // this is needed for the parallel debugger
+        public static int WaitAny(Task[] tasks, TimeSpan timeout)
+        {
+            long totalMilliseconds = (long)timeout.TotalMilliseconds;
+            if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue)
+            {
+                ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.timeout);
+            }
+
+            return WaitAnyCore(tasks, (int)totalMilliseconds, default);
+        }
+
+        /// <summary>
+        /// Waits for any of the provided <see cref="Task"/> objects to complete execution.
+        /// </summary>
+        /// <param name="tasks">
+        /// An array of <see cref="Task"/> instances on which to wait.
+        /// </param>
+        /// <param name="cancellationToken">
+        /// A <see cref="CancellationToken"/> to observe while waiting for a task to complete.
+        /// </param>
+        /// <returns>
+        /// The index of the completed task in the <paramref name="tasks"/> array argument.
+        /// </returns>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="tasks"/> argument is null.
+        /// </exception>
+        /// <exception cref="T:System.ArgumentException">
+        /// The <paramref name="tasks"/> argument contains a null element.
+        /// </exception>
+        /// <exception cref="T:System.OperationCanceledException">
+        /// The <paramref name="cancellationToken"/> was canceled.
+        /// </exception>
+        [MethodImpl(MethodImplOptions.NoOptimization)]  // this is needed for the parallel debugger
+        public static int WaitAny(Task[] tasks, CancellationToken cancellationToken)
+        {
+            return WaitAnyCore(tasks, Timeout.Infinite, cancellationToken);
+        }
+
+        /// <summary>
+        /// Waits for any of the provided <see cref="Task"/> objects to complete execution.
+        /// </summary>
+        /// <param name="tasks">
+        /// An array of <see cref="Task"/> instances on which to wait.
+        /// </param>
+        /// <param name="millisecondsTimeout">
+        /// The number of milliseconds to wait, or <see cref="System.Threading.Timeout.Infinite"/> (-1) to
+        /// wait indefinitely.
+        /// </param>
+        /// <returns>
+        /// The index of the completed task in the <paramref name="tasks"/> array argument, or -1 if the
+        /// timeout occurred.
+        /// </returns>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="tasks"/> argument is null.
+        /// </exception>
+        /// <exception cref="T:System.ArgumentException">
+        /// The <paramref name="tasks"/> argument contains a null element.
+        /// </exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">
+        /// <paramref name="millisecondsTimeout"/> is a negative number other than -1, which represents an
+        /// infinite time-out.
+        /// </exception>
+        [MethodImpl(MethodImplOptions.NoOptimization)]  // this is needed for the parallel debugger
+        public static int WaitAny(Task[] tasks, int millisecondsTimeout)
+        {
+            return WaitAnyCore(tasks, millisecondsTimeout, default);
+        }
+
+        /// <summary>
+        /// Waits for any of the provided <see cref="Task"/> objects to complete execution.
+        /// </summary>
+        /// <param name="tasks">
+        /// An array of <see cref="Task"/> instances on which to wait.
+        /// </param>
+        /// <param name="millisecondsTimeout">
+        /// The number of milliseconds to wait, or <see cref="System.Threading.Timeout.Infinite"/> (-1) to
+        /// wait indefinitely.
+        /// </param>
+        /// <param name="cancellationToken">
+        /// A <see cref="CancellationToken"/> to observe while waiting for a task to complete.
+        /// </param>
+        /// <returns>
+        /// The index of the completed task in the <paramref name="tasks"/> array argument, or -1 if the
+        /// timeout occurred.
+        /// </returns>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="tasks"/> argument is null.
+        /// </exception>
+        /// <exception cref="T:System.ArgumentException">
+        /// The <paramref name="tasks"/> argument contains a null element.
+        /// </exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">
+        /// <paramref name="millisecondsTimeout"/> is a negative number other than -1, which represents an
+        /// infinite time-out.
+        /// </exception>
+        /// <exception cref="T:System.OperationCanceledException">
+        /// The <paramref name="cancellationToken"/> was canceled.
+        /// </exception>
+        [MethodImpl(MethodImplOptions.NoOptimization)]  // this is needed for the parallel debugger
+        public static int WaitAny(Task[] tasks, int millisecondsTimeout, CancellationToken cancellationToken) =>
+            WaitAnyCore(tasks, millisecondsTimeout, cancellationToken);
+
+        // Separated out to allow it to be optimized (caller is marked NoOptimization for VS parallel debugger
+        // to be able to inspect arguments).
+        private static int WaitAnyCore(Task[] tasks, int millisecondsTimeout, CancellationToken cancellationToken)
+        {
+            if (tasks == null)
+            {
+                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.tasks);
+            }
+            if (millisecondsTimeout < -1)
+            {
+                ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.millisecondsTimeout);
+            }
+
+            cancellationToken.ThrowIfCancellationRequested(); // early check before we make any allocations
+
+            int signaledTaskIndex = -1;
+
+            // Make a pass through the loop to check for any tasks that may have
+            // already been completed, and to verify that no tasks are null.
+
+            for (int taskIndex = 0; taskIndex < tasks.Length; taskIndex++)
+            {
+                Task task = tasks[taskIndex];
+
+                if (task == null)
+                {
+                    ThrowHelper.ThrowArgumentException(ExceptionResource.Task_WaitMulti_NullTask, ExceptionArgument.tasks);
+                }
+
+                if (signaledTaskIndex == -1 && task.IsCompleted)
+                {
+                    // We found our first completed task.  Store it, but we can't just return here,
+                    // as we still need to validate the whole array for nulls.
+                    signaledTaskIndex = taskIndex;
+                }
+            }
+
+            if (signaledTaskIndex == -1 && tasks.Length != 0)
+            {
+                Task<Task> firstCompleted = TaskFactory.CommonCWAnyLogic(tasks);
+                bool waitCompleted = firstCompleted.Wait(millisecondsTimeout, cancellationToken);
+                if (waitCompleted)
+                {
+                    Debug.Assert(firstCompleted.Status == TaskStatus.RanToCompletion);
+                    signaledTaskIndex = Array.IndexOf(tasks, firstCompleted.Result);
+                    Debug.Assert(signaledTaskIndex >= 0);
+                }
+                else
+                {
+                    TaskFactory.CommonCWAnyLogicCleanup(firstCompleted);
+                }
+            }
+
+            // We need to prevent the tasks array from being GC'ed until we come out of the wait.
+            // This is necessary so that the Parallel Debugger can traverse it during the long wait 
+            // and deduce waiter/waitee relationships
+            GC.KeepAlive(tasks);
+
+            // Return the index
+            return signaledTaskIndex;
+        }
+
+        #region FromResult / FromException / FromCanceled
+
+        /// <summary>Creates a <see cref="Task{TResult}"/> that's completed successfully with the specified result.</summary>
+        /// <typeparam name="TResult">The type of the result returned by the task.</typeparam>
+        /// <param name="result">The result to store into the completed task.</param>
+        /// <returns>The successfully completed task.</returns>
+        public static Task<TResult> FromResult<TResult>(TResult result)
+        {
+            return new Task<TResult>(result);
+        }
+
+        /// <summary>Creates a <see cref="Task{TResult}"/> that's completed exceptionally with the specified exception.</summary>
+        /// <param name="exception">The exception with which to complete the task.</param>
+        /// <returns>The faulted task.</returns>
+        public static Task FromException(Exception exception)
+        {
+            return FromException<VoidTaskResult>(exception);
+        }
+
+        /// <summary>Creates a <see cref="Task{TResult}"/> that's completed exceptionally with the specified exception.</summary>
+        /// <typeparam name="TResult">The type of the result returned by the task.</typeparam>
+        /// <param name="exception">The exception with which to complete the task.</param>
+        /// <returns>The faulted task.</returns>
+        public static Task<TResult> FromException<TResult>(Exception exception)
+        {
+            if (exception == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.exception);
+
+            var task = new Task<TResult>();
+            bool succeeded = task.TrySetException(exception);
+            Debug.Assert(succeeded, "This should always succeed on a new task.");
+            return task;
+        }
+
+        /// <summary>Creates a <see cref="Task"/> that's completed due to cancellation with the specified token.</summary>
+        /// <param name="cancellationToken">The token with which to complete the task.</param>
+        /// <returns>The canceled task.</returns>
+        public static Task FromCanceled(CancellationToken cancellationToken)
+        {
+            if (!cancellationToken.IsCancellationRequested)
+                ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.cancellationToken);
+            return new Task(true, TaskCreationOptions.None, cancellationToken);
+        }
+
+        /// <summary>Creates a <see cref="Task{TResult}"/> that's completed due to cancellation with the specified token.</summary>
+        /// <typeparam name="TResult">The type of the result returned by the task.</typeparam>
+        /// <param name="cancellationToken">The token with which to complete the task.</param>
+        /// <returns>The canceled task.</returns>
+        public static Task<TResult> FromCanceled<TResult>(CancellationToken cancellationToken)
+        {
+            if (!cancellationToken.IsCancellationRequested)
+                ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.cancellationToken);
+            return new Task<TResult>(true, default, TaskCreationOptions.None, cancellationToken);
+        }
+
+        /// <summary>Creates a <see cref="Task{TResult}"/> that's completed due to cancellation with the specified exception.</summary>
+        /// <typeparam name="TResult">The type of the result returned by the task.</typeparam>
+        /// <param name="exception">The exception with which to complete the task.</param>
+        /// <returns>The canceled task.</returns>
+        internal static Task<TResult> FromCancellation<TResult>(OperationCanceledException exception)
+        {
+            if (exception == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.exception);
+
+            var task = new Task<TResult>();
+            bool succeeded = task.TrySetCanceled(exception.CancellationToken, exception);
+            Debug.Assert(succeeded, "This should always succeed on a new task.");
+            return task;
+        }
+
+        #endregion
+
+        #region Run methods
+
+
+        /// <summary>
+        /// Queues the specified work to run on the ThreadPool and returns a Task handle for that work.
+        /// </summary>
+        /// <param name="action">The work to execute asynchronously</param>
+        /// <returns>A Task that represents the work queued to execute in the ThreadPool.</returns>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="action"/> parameter was null.
+        /// </exception>
+        public static Task Run(Action action)
+        {
+            return Task.InternalStartNew(null, action, null, default, TaskScheduler.Default,
+                TaskCreationOptions.DenyChildAttach, InternalTaskOptions.None);
+        }
+
+        /// <summary>
+        /// Queues the specified work to run on the ThreadPool and returns a Task handle for that work.
+        /// </summary>
+        /// <param name="action">The work to execute asynchronously</param>
+        /// <param name="cancellationToken">A cancellation token that should be used to cancel the work</param>
+        /// <returns>A Task that represents the work queued to execute in the ThreadPool.</returns>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="action"/> parameter was null.
+        /// </exception>
+        /// <exception cref="T:System.ObjectDisposedException">
+        /// The <see cref="T:System.CancellationTokenSource"/> associated with <paramref name="cancellationToken"/> was disposed.
+        /// </exception>
+        public static Task Run(Action action, CancellationToken cancellationToken)
+        {
+            return Task.InternalStartNew(null, action, null, cancellationToken, TaskScheduler.Default,
+                TaskCreationOptions.DenyChildAttach, InternalTaskOptions.None);
+        }
+
+        /// <summary>
+        /// Queues the specified work to run on the ThreadPool and returns a Task(TResult) handle for that work.
+        /// </summary>
+        /// <param name="function">The work to execute asynchronously</param>
+        /// <returns>A Task(TResult) that represents the work queued to execute in the ThreadPool.</returns>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="function"/> parameter was null.
+        /// </exception>
+        public static Task<TResult> Run<TResult>(Func<TResult> function)
+        {
+            return Task<TResult>.StartNew(null, function, default,
+                TaskCreationOptions.DenyChildAttach, InternalTaskOptions.None, TaskScheduler.Default);
+        }
+
+        /// <summary>
+        /// Queues the specified work to run on the ThreadPool and returns a Task(TResult) handle for that work.
+        /// </summary>
+        /// <param name="function">The work to execute asynchronously</param>
+        /// <param name="cancellationToken">A cancellation token that should be used to cancel the work</param>
+        /// <returns>A Task(TResult) that represents the work queued to execute in the ThreadPool.</returns>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="function"/> parameter was null.
+        /// </exception>
+        /// <exception cref="T:System.ObjectDisposedException">
+        /// The <see cref="T:System.CancellationTokenSource"/> associated with <paramref name="cancellationToken"/> was disposed.
+        /// </exception>
+        public static Task<TResult> Run<TResult>(Func<TResult> function, CancellationToken cancellationToken)
+        {
+            return Task<TResult>.StartNew(null, function, cancellationToken,
+                TaskCreationOptions.DenyChildAttach, InternalTaskOptions.None, TaskScheduler.Default);
+        }
+
+        /// <summary>
+        /// Queues the specified work to run on the ThreadPool and returns a proxy for the
+        /// Task returned by <paramref name="function"/>.
+        /// </summary>
+        /// <param name="function">The work to execute asynchronously</param>
+        /// <returns>A Task that represents a proxy for the Task returned by <paramref name="function"/>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="function"/> parameter was null.
+        /// </exception>
+        public static Task Run(Func<Task> function)
+        {
+            return Run(function, default);
+        }
+
+
+        /// <summary>
+        /// Queues the specified work to run on the ThreadPool and returns a proxy for the
+        /// Task returned by <paramref name="function"/>.
+        /// </summary>
+        /// <param name="function">The work to execute asynchronously</param>
+        /// <param name="cancellationToken">A cancellation token that should be used to cancel the work</param>
+        /// <returns>A Task that represents a proxy for the Task returned by <paramref name="function"/>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="function"/> parameter was null.
+        /// </exception>
+        /// <exception cref="T:System.ObjectDisposedException">
+        /// The <see cref="T:System.CancellationTokenSource"/> associated with <paramref name="cancellationToken"/> was disposed.
+        /// </exception>
+        public static Task Run(Func<Task> function, CancellationToken cancellationToken)
+        {
+            // Check arguments
+            if (function == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.function);
+
+            // Short-circuit if we are given a pre-canceled token
+            if (cancellationToken.IsCancellationRequested)
+                return Task.FromCanceled(cancellationToken);
+
+            // Kick off initial Task, which will call the user-supplied function and yield a Task.
+            Task<Task> task1 = Task<Task>.Factory.StartNew(function, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
+
+            // Create a promise-style Task to be used as a proxy for the operation
+            // Set lookForOce == true so that unwrap logic can be on the lookout for OCEs thrown as faults from task1, to support in-delegate cancellation.
+            UnwrapPromise<VoidTaskResult> promise = new UnwrapPromise<VoidTaskResult>(task1, lookForOce: true);
+
+            return promise;
+        }
+
+        /// <summary>
+        /// Queues the specified work to run on the ThreadPool and returns a proxy for the
+        /// Task(TResult) returned by <paramref name="function"/>.
+        /// </summary>
+        /// <typeparam name="TResult">The type of the result returned by the proxy Task.</typeparam>
+        /// <param name="function">The work to execute asynchronously</param>
+        /// <returns>A Task(TResult) that represents a proxy for the Task(TResult) returned by <paramref name="function"/>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="function"/> parameter was null.
+        /// </exception>
+        public static Task<TResult> Run<TResult>(Func<Task<TResult>> function)
+        {
+            return Run(function, default);
+        }
+
+        /// <summary>
+        /// Queues the specified work to run on the ThreadPool and returns a proxy for the
+        /// Task(TResult) returned by <paramref name="function"/>.
+        /// </summary>
+        /// <typeparam name="TResult">The type of the result returned by the proxy Task.</typeparam>
+        /// <param name="function">The work to execute asynchronously</param>
+        /// <param name="cancellationToken">A cancellation token that should be used to cancel the work</param>
+        /// <returns>A Task(TResult) that represents a proxy for the Task(TResult) returned by <paramref name="function"/>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="function"/> parameter was null.
+        /// </exception>
+        public static Task<TResult> Run<TResult>(Func<Task<TResult>> function, CancellationToken cancellationToken)
+        {
+            // Check arguments
+            if (function == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.function);
+
+            // Short-circuit if we are given a pre-canceled token
+            if (cancellationToken.IsCancellationRequested)
+                return Task.FromCanceled<TResult>(cancellationToken);
+
+            // Kick off initial Task, which will call the user-supplied function and yield a Task.
+            Task<Task<TResult>> task1 = Task<Task<TResult>>.Factory.StartNew(function, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
+
+            // Create a promise-style Task to be used as a proxy for the operation
+            // Set lookForOce == true so that unwrap logic can be on the lookout for OCEs thrown as faults from task1, to support in-delegate cancellation.
+            UnwrapPromise<TResult> promise = new UnwrapPromise<TResult>(task1, lookForOce: true);
+
+            return promise;
+        }
+
+
+        #endregion
+
+        #region Delay methods
+
+        /// <summary>
+        /// Creates a Task that will complete after a time delay.
+        /// </summary>
+        /// <param name="delay">The time span to wait before completing the returned Task</param>
+        /// <returns>A Task that represents the time delay</returns>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">
+        /// The <paramref name="delay"/> is less than -1 or greater than int.MaxValue.
+        /// </exception>
+        /// <remarks>
+        /// After the specified time delay, the Task is completed in RanToCompletion state.
+        /// </remarks>
+        public static Task Delay(TimeSpan delay)
+        {
+            return Delay(delay, default);
+        }
+
+        /// <summary>
+        /// Creates a Task that will complete after a time delay.
+        /// </summary>
+        /// <param name="delay">The time span to wait before completing the returned Task</param>
+        /// <param name="cancellationToken">The cancellation token that will be checked prior to completing the returned Task</param>
+        /// <returns>A Task that represents the time delay</returns>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">
+        /// The <paramref name="delay"/> is less than -1 or greater than int.MaxValue.
+        /// </exception>
+        /// <exception cref="T:System.ObjectDisposedException">
+        /// The provided <paramref name="cancellationToken"/> has already been disposed.
+        /// </exception>        
+        /// <remarks>
+        /// If the cancellation token is signaled before the specified time delay, then the Task is completed in
+        /// Canceled state.  Otherwise, the Task is completed in RanToCompletion state once the specified time
+        /// delay has expired.
+        /// </remarks>        
+        public static Task Delay(TimeSpan delay, CancellationToken cancellationToken)
+        {
+            long totalMilliseconds = (long)delay.TotalMilliseconds;
+            if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue)
+            {
+                ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.delay, ExceptionResource.Task_Delay_InvalidDelay);
+            }
+
+            return Delay((int)totalMilliseconds, cancellationToken);
+        }
+
+        /// <summary>
+        /// Creates a Task that will complete after a time delay.
+        /// </summary>
+        /// <param name="millisecondsDelay">The number of milliseconds to wait before completing the returned Task</param>
+        /// <returns>A Task that represents the time delay</returns>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">
+        /// The <paramref name="millisecondsDelay"/> is less than -1.
+        /// </exception>
+        /// <remarks>
+        /// After the specified time delay, the Task is completed in RanToCompletion state.
+        /// </remarks>
+        public static Task Delay(int millisecondsDelay)
+        {
+            return Delay(millisecondsDelay, default);
+        }
+
+        /// <summary>
+        /// Creates a Task that will complete after a time delay.
+        /// </summary>
+        /// <param name="millisecondsDelay">The number of milliseconds to wait before completing the returned Task</param>
+        /// <param name="cancellationToken">The cancellation token that will be checked prior to completing the returned Task</param>
+        /// <returns>A Task that represents the time delay</returns>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">
+        /// The <paramref name="millisecondsDelay"/> is less than -1.
+        /// </exception>
+        /// <exception cref="T:System.ObjectDisposedException">
+        /// The provided <paramref name="cancellationToken"/> has already been disposed.
+        /// </exception>        
+        /// <remarks>
+        /// If the cancellation token is signaled before the specified time delay, then the Task is completed in
+        /// Canceled state.  Otherwise, the Task is completed in RanToCompletion state once the specified time
+        /// delay has expired.
+        /// </remarks>        
+        public static Task Delay(int millisecondsDelay, CancellationToken cancellationToken)
+        {
+            // Throw on non-sensical time
+            if (millisecondsDelay < -1)
+            {
+                ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.millisecondsDelay, ExceptionResource.Task_Delay_InvalidMillisecondsDelay);
+            }
+
+            // some short-cuts in case quick completion is in order
+            if (cancellationToken.IsCancellationRequested)
+            {
+                // return a Task created as already-Canceled
+                return Task.FromCanceled(cancellationToken);
+            }
+            else if (millisecondsDelay == 0)
+            {
+                // return a Task created as already-RanToCompletion
+                return Task.CompletedTask;
+            }
+
+            // Construct a promise-style Task to encapsulate our return value
+            var promise = new DelayPromise(cancellationToken);
+
+            // Register our cancellation token, if necessary.
+            if (cancellationToken.CanBeCanceled)
+            {
+                promise.Registration = cancellationToken.UnsafeRegister(state => ((DelayPromise)state).Complete(), promise);
+            }
+
+            // ... and create our timer and make sure that it stays rooted.
+            if (millisecondsDelay != Timeout.Infinite) // no need to create the timer if it's an infinite timeout
+            {
+                promise.Timer = new TimerQueueTimer(state => ((DelayPromise)state).Complete(), promise, (uint)millisecondsDelay, Timeout.UnsignedInfinite, flowExecutionContext: false);
+            }
+
+            // Return the timer proxy task
+            return promise;
+        }
+
+        /// <summary>Task that also stores the completion closure and logic for Task.Delay implementation.</summary>
+        private sealed class DelayPromise : Task<VoidTaskResult>
+        {
+            internal DelayPromise(CancellationToken token)
+                : base()
+            {
+                this.Token = token;
+                if (DebuggerSupport.LoggingOn)
+                    DebuggerSupport.TraceOperationCreation(CausalityTraceLevel.Required, this, "Task.Delay", 0);
+                DebuggerSupport.AddToActiveTasks(this);
+            }
+
+            internal readonly CancellationToken Token;
+            internal CancellationTokenRegistration Registration;
+            internal TimerQueueTimer Timer;
+
+            internal void Complete()
+            {
+                // Transition the task to completed.
+                bool setSucceeded;
+
+                if (Token.IsCancellationRequested)
+                {
+                    setSucceeded = TrySetCanceled(Token);
+                }
+                else
+                {
+                    if (DebuggerSupport.LoggingOn)
+                        DebuggerSupport.TraceOperationCompletion(CausalityTraceLevel.Required, this, AsyncStatus.Completed);
+                    DebuggerSupport.RemoveFromActiveTasks(this);
+
+                    setSucceeded = TrySetResult(default);
+                }
+
+                // If we set the value, also clean up.
+                if (setSucceeded)
+                {
+                    Timer?.Close();
+                    Registration.Dispose();
+                }
+            }
+        }
+        #endregion
+
+        #region WhenAll
+        /// <summary>
+        /// Creates a task that will complete when all of the supplied tasks have completed.
+        /// </summary>
+        /// <param name="tasks">The tasks to wait on for completion.</param>
+        /// <returns>A task that represents the completion of all of the supplied tasks.</returns>
+        /// <remarks>
+        /// <para>
+        /// If any of the supplied tasks completes in a faulted state, the returned task will also complete in a Faulted state, 
+        /// where its exceptions will contain the aggregation of the set of unwrapped exceptions from each of the supplied tasks.  
+        /// </para>
+        /// <para>
+        /// If none of the supplied tasks faulted but at least one of them was canceled, the returned task will end in the Canceled state.
+        /// </para>
+        /// <para>
+        /// If none of the tasks faulted and none of the tasks were canceled, the resulting task will end in the RanToCompletion state.   
+        /// </para>
+        /// <para>
+        /// If the supplied array/enumerable contains no tasks, the returned task will immediately transition to a RanToCompletion 
+        /// state before it's returned to the caller.  
+        /// </para>
+        /// </remarks>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="tasks"/> argument was null.
+        /// </exception>
+        /// <exception cref="T:System.ArgumentException">
+        /// The <paramref name="tasks"/> collection contained a null task.
+        /// </exception>
+        public static Task WhenAll(IEnumerable<Task> tasks)
+        {
+            // Take a more efficient path if tasks is actually an array
+            Task[] taskArray = tasks as Task[];
+            if (taskArray != null)
+            {
+                return WhenAll(taskArray);
+            }
+
+            // Skip a List allocation/copy if tasks is a collection
+            ICollection<Task> taskCollection = tasks as ICollection<Task>;
+            if (taskCollection != null)
+            {
+                int index = 0;
+                taskArray = new Task[taskCollection.Count];
+                foreach (var task in tasks)
+                {
+                    if (task == null) ThrowHelper.ThrowArgumentException(ExceptionResource.Task_MultiTaskContinuation_NullTask, ExceptionArgument.tasks);
+                    taskArray[index++] = task;
+                }
+                return InternalWhenAll(taskArray);
+            }
+
+            // Do some argument checking and convert tasks to a List (and later an array).
+            if (tasks == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.tasks);
+            List<Task> taskList = new List<Task>();
+            foreach (Task task in tasks)
+            {
+                if (task == null) ThrowHelper.ThrowArgumentException(ExceptionResource.Task_MultiTaskContinuation_NullTask, ExceptionArgument.tasks);
+                taskList.Add(task);
+            }
+
+            // Delegate the rest to InternalWhenAll()
+            return InternalWhenAll(taskList.ToArray());
+        }
+
+        /// <summary>
+        /// Creates a task that will complete when all of the supplied tasks have completed.
+        /// </summary>
+        /// <param name="tasks">The tasks to wait on for completion.</param>
+        /// <returns>A task that represents the completion of all of the supplied tasks.</returns>
+        /// <remarks>
+        /// <para>
+        /// If any of the supplied tasks completes in a faulted state, the returned task will also complete in a Faulted state, 
+        /// where its exceptions will contain the aggregation of the set of unwrapped exceptions from each of the supplied tasks.  
+        /// </para>
+        /// <para>
+        /// If none of the supplied tasks faulted but at least one of them was canceled, the returned task will end in the Canceled state.
+        /// </para>
+        /// <para>
+        /// If none of the tasks faulted and none of the tasks were canceled, the resulting task will end in the RanToCompletion state.   
+        /// </para>
+        /// <para>
+        /// If the supplied array/enumerable contains no tasks, the returned task will immediately transition to a RanToCompletion 
+        /// state before it's returned to the caller.  
+        /// </para>
+        /// </remarks>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="tasks"/> argument was null.
+        /// </exception>
+        /// <exception cref="T:System.ArgumentException">
+        /// The <paramref name="tasks"/> array contained a null task.
+        /// </exception>
+        public static Task WhenAll(params Task[] tasks)
+        {
+            // Do some argument checking and make a defensive copy of the tasks array
+            if (tasks == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.tasks);
+
+            int taskCount = tasks.Length;
+            if (taskCount == 0) return InternalWhenAll(tasks); // Small optimization in the case of an empty array.
+
+            Task[] tasksCopy = new Task[taskCount];
+            for (int i = 0; i < taskCount; i++)
+            {
+                Task task = tasks[i];
+                if (task == null) ThrowHelper.ThrowArgumentException(ExceptionResource.Task_MultiTaskContinuation_NullTask, ExceptionArgument.tasks);
+                tasksCopy[i] = task;
+            }
+
+            // The rest can be delegated to InternalWhenAll()
+            return InternalWhenAll(tasksCopy);
+        }
+
+        // Some common logic to support WhenAll() methods
+        // tasks should be a defensive copy.
+        private static Task InternalWhenAll(Task[] tasks)
+        {
+            Debug.Assert(tasks != null, "Expected a non-null tasks array");
+            return (tasks.Length == 0) ? // take shortcut if there are no tasks upon which to wait
+                Task.CompletedTask :
+                new WhenAllPromise(tasks);
+        }
+
+        // A Task<VoidTaskResult> that gets completed when all of its constituent tasks complete.
+        // Completion logic will analyze the antecedents in order to choose completion status.
+        // This type allows us to replace this logic:
+        //      Task<VoidTaskResult> promise = new Task<VoidTaskResult>(...);
+        //      Action<Task> completionAction = delegate { <completion logic>};
+        //      TaskFactory.CommonCWAllLogic(tasksCopy).AddCompletionAction(completionAction);
+        //      return promise;
+        // which involves several allocations, with this logic:
+        //      return new WhenAllPromise(tasksCopy);
+        // which saves a couple of allocations and enables debugger notification specialization.
+        //
+        // Used in InternalWhenAll(Task[])
+        private sealed class WhenAllPromise : Task<VoidTaskResult>, ITaskCompletionAction
+        {
+            /// <summary>
+            /// Stores all of the constituent tasks.  Tasks clear themselves out of this
+            /// array as they complete, but only if they don't have their wait notification bit set.
+            /// </summary>
+            private readonly Task[] m_tasks;
+            /// <summary>The number of tasks remaining to complete.</summary>
+            private int m_count;
+
+            internal WhenAllPromise(Task[] tasks) :
+                base()
+            {
+                Debug.Assert(tasks != null, "Expected a non-null task array");
+                Debug.Assert(tasks.Length > 0, "Expected a non-zero length task array");
+
+                if (DebuggerSupport.LoggingOn)
+                    DebuggerSupport.TraceOperationCreation(CausalityTraceLevel.Required, this, "Task.WhenAll", 0);
+                DebuggerSupport.AddToActiveTasks(this);
+
+                m_tasks = tasks;
+                m_count = tasks.Length;
+
+                foreach (var task in tasks)
+                {
+                    if (task.IsCompleted) this.Invoke(task); // short-circuit the completion action, if possible
+                    else task.AddCompletionAction(this); // simple completion action
+                }
+            }
+
+            public void Invoke(Task completedTask)
+            {
+                if (DebuggerSupport.LoggingOn)
+                    DebuggerSupport.TraceOperationRelation(CausalityTraceLevel.Important, this, CausalityRelation.Join);
+
+                // Decrement the count, and only continue to complete the promise if we're the last one.
+                if (Interlocked.Decrement(ref m_count) == 0)
+                {
+                    // Set up some accounting variables
+                    List<ExceptionDispatchInfo> observedExceptions = null;
+                    Task canceledTask = null;
+
+                    // Loop through antecedents:
+                    //   If any one of them faults, the result will be faulted
+                    //   If none fault, but at least one is canceled, the result will be canceled
+                    //   If none fault or are canceled, then result will be RanToCompletion
+                    for (int i = 0; i < m_tasks.Length; i++)
+                    {
+                        var task = m_tasks[i];
+                        Debug.Assert(task != null, "Constituent task in WhenAll should never be null");
+
+                        if (task.IsFaulted)
+                        {
+                            if (observedExceptions == null) observedExceptions = new List<ExceptionDispatchInfo>();
+                            observedExceptions.AddRange(task.GetExceptionDispatchInfos());
+                        }
+                        else if (task.IsCanceled)
+                        {
+                            if (canceledTask == null) canceledTask = task; // use the first task that's canceled
+                        }
+
+                        // Regardless of completion state, if the task has its debug bit set, transfer it to the
+                        // WhenAll task.  We must do this before we complete the task.
+                        if (task.IsWaitNotificationEnabled) this.SetNotificationForWaitCompletion(enabled: true);
+                        else m_tasks[i] = null; // avoid holding onto tasks unnecessarily
+                    }
+
+                    if (observedExceptions != null)
+                    {
+                        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
+
+                        TrySetException(observedExceptions);
+                    }
+                    else if (canceledTask != null)
+                    {
+                        TrySetCanceled(canceledTask.CancellationToken, canceledTask.GetCancellationExceptionDispatchInfo());
+                    }
+                    else
+                    {
+                        if (DebuggerSupport.LoggingOn)
+                            DebuggerSupport.TraceOperationCompletion(CausalityTraceLevel.Required, this, AsyncStatus.Completed);
+                        DebuggerSupport.RemoveFromActiveTasks(this);
+
+                        TrySetResult(default);
+                    }
+                }
+                Debug.Assert(m_count >= 0, "Count should never go below 0");
+            }
+
+            public bool InvokeMayRunArbitraryCode { get { return true; } }
+
+            /// <summary>
+            /// Returns whether we should notify the debugger of a wait completion.  This returns 
+            /// true iff at least one constituent task has its bit set.
+            /// </summary>
+            internal override bool ShouldNotifyDebuggerOfWaitCompletion
+            {
+                get
+                {
+                    return
+                        base.ShouldNotifyDebuggerOfWaitCompletion &&
+                        Task.AnyTaskRequiresNotifyDebuggerOfWaitCompletion(m_tasks);
+                }
+            }
+        }
+
+        /// <summary>
+        /// Creates a task that will complete when all of the supplied tasks have completed.
+        /// </summary>
+        /// <param name="tasks">The tasks to wait on for completion.</param>
+        /// <returns>A task that represents the completion of all of the supplied tasks.</returns>
+        /// <remarks>
+        /// <para>
+        /// If any of the supplied tasks completes in a faulted state, the returned task will also complete in a Faulted state, 
+        /// where its exceptions will contain the aggregation of the set of unwrapped exceptions from each of the supplied tasks.  
+        /// </para>
+        /// <para>
+        /// If none of the supplied tasks faulted but at least one of them was canceled, the returned task will end in the Canceled state.
+        /// </para>
+        /// <para>
+        /// If none of the tasks faulted and none of the tasks were canceled, the resulting task will end in the RanToCompletion state.  
+        /// The Result of the returned task will be set to an array containing all of the results of the 
+        /// supplied tasks in the same order as they were provided (e.g. if the input tasks array contained t1, t2, t3, the output 
+        /// task's Result will return an TResult[] where arr[0] == t1.Result, arr[1] == t2.Result, and arr[2] == t3.Result). 
+        /// </para>
+        /// <para>
+        /// If the supplied array/enumerable contains no tasks, the returned task will immediately transition to a RanToCompletion 
+        /// state before it's returned to the caller.  The returned TResult[] will be an array of 0 elements.
+        /// </para>
+        /// </remarks>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="tasks"/> argument was null.
+        /// </exception>
+        /// <exception cref="T:System.ArgumentException">
+        /// The <paramref name="tasks"/> collection contained a null task.
+        /// </exception>       
+        public static Task<TResult[]> WhenAll<TResult>(IEnumerable<Task<TResult>> tasks)
+        {
+            // Take a more efficient route if tasks is actually an array
+            Task<TResult>[] taskArray = tasks as Task<TResult>[];
+            if (taskArray != null)
+            {
+                return WhenAll<TResult>(taskArray);
+            }
+
+            // Skip a List allocation/copy if tasks is a collection
+            ICollection<Task<TResult>> taskCollection = tasks as ICollection<Task<TResult>>;
+            if (taskCollection != null)
+            {
+                int index = 0;
+                taskArray = new Task<TResult>[taskCollection.Count];
+                foreach (var task in tasks)
+                {
+                    if (task == null) ThrowHelper.ThrowArgumentException(ExceptionResource.Task_MultiTaskContinuation_NullTask, ExceptionArgument.tasks);
+                    taskArray[index++] = task;
+                }
+                return InternalWhenAll<TResult>(taskArray);
+            }
+
+            // Do some argument checking and convert tasks into a List (later an array)
+            if (tasks == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.tasks);
+            List<Task<TResult>> taskList = new List<Task<TResult>>();
+            foreach (Task<TResult> task in tasks)
+            {
+                if (task == null) ThrowHelper.ThrowArgumentException(ExceptionResource.Task_MultiTaskContinuation_NullTask, ExceptionArgument.tasks);
+                taskList.Add(task);
+            }
+
+            // Delegate the rest to InternalWhenAll<TResult>().
+            return InternalWhenAll<TResult>(taskList.ToArray());
+        }
+
+        /// <summary>
+        /// Creates a task that will complete when all of the supplied tasks have completed.
+        /// </summary>
+        /// <param name="tasks">The tasks to wait on for completion.</param>
+        /// <returns>A task that represents the completion of all of the supplied tasks.</returns>
+        /// <remarks>
+        /// <para>
+        /// If any of the supplied tasks completes in a faulted state, the returned task will also complete in a Faulted state, 
+        /// where its exceptions will contain the aggregation of the set of unwrapped exceptions from each of the supplied tasks.  
+        /// </para>
+        /// <para>
+        /// If none of the supplied tasks faulted but at least one of them was canceled, the returned task will end in the Canceled state.
+        /// </para>
+        /// <para>
+        /// If none of the tasks faulted and none of the tasks were canceled, the resulting task will end in the RanToCompletion state.  
+        /// The Result of the returned task will be set to an array containing all of the results of the 
+        /// supplied tasks in the same order as they were provided (e.g. if the input tasks array contained t1, t2, t3, the output 
+        /// task's Result will return an TResult[] where arr[0] == t1.Result, arr[1] == t2.Result, and arr[2] == t3.Result). 
+        /// </para>
+        /// <para>
+        /// If the supplied array/enumerable contains no tasks, the returned task will immediately transition to a RanToCompletion 
+        /// state before it's returned to the caller.  The returned TResult[] will be an array of 0 elements.
+        /// </para>
+        /// </remarks>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="tasks"/> argument was null.
+        /// </exception>
+        /// <exception cref="T:System.ArgumentException">
+        /// The <paramref name="tasks"/> array contained a null task.
+        /// </exception>
+        public static Task<TResult[]> WhenAll<TResult>(params Task<TResult>[] tasks)
+        {
+            // Do some argument checking and make a defensive copy of the tasks array
+            if (tasks == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.tasks);
+
+            int taskCount = tasks.Length;
+            if (taskCount == 0) return InternalWhenAll<TResult>(tasks); // small optimization in the case of an empty task array
+
+            Task<TResult>[] tasksCopy = new Task<TResult>[taskCount];
+            for (int i = 0; i < taskCount; i++)
+            {
+                Task<TResult> task = tasks[i];
+                if (task == null) ThrowHelper.ThrowArgumentException(ExceptionResource.Task_MultiTaskContinuation_NullTask, ExceptionArgument.tasks);
+                tasksCopy[i] = task;
+            }
+
+            // Delegate the rest to InternalWhenAll<TResult>()
+            return InternalWhenAll<TResult>(tasksCopy);
+        }
+
+        // Some common logic to support WhenAll<TResult> methods
+        private static Task<TResult[]> InternalWhenAll<TResult>(Task<TResult>[] tasks)
+        {
+            Debug.Assert(tasks != null, "Expected a non-null tasks array");
+            return (tasks.Length == 0) ? // take shortcut if there are no tasks upon which to wait
+                new Task<TResult[]>(false, new TResult[0], TaskCreationOptions.None, default) :
+                new WhenAllPromise<TResult>(tasks);
+        }
+
+        // A Task<T> that gets completed when all of its constituent tasks complete.
+        // Completion logic will analyze the antecedents in order to choose completion status.
+        // See comments for non-generic version of WhenAllPromise class.
+        //
+        // Used in InternalWhenAll<TResult>(Task<TResult>[])
+        private sealed class WhenAllPromise<T> : Task<T[]>, ITaskCompletionAction
+        {
+            /// <summary>
+            /// Stores all of the constituent tasks.  Tasks clear themselves out of this
+            /// array as they complete, but only if they don't have their wait notification bit set.
+            /// </summary>
+            private readonly Task<T>[] m_tasks;
+            /// <summary>The number of tasks remaining to complete.</summary>
+            private int m_count;
+
+            internal WhenAllPromise(Task<T>[] tasks) :
+                base()
+            {
+                Debug.Assert(tasks != null, "Expected a non-null task array");
+                Debug.Assert(tasks.Length > 0, "Expected a non-zero length task array");
+
+                m_tasks = tasks;
+                m_count = tasks.Length;
+
+                if (DebuggerSupport.LoggingOn)
+                    DebuggerSupport.TraceOperationCreation(CausalityTraceLevel.Required, this, "Task.WhenAll", 0);
+                DebuggerSupport.AddToActiveTasks(this);
+
+                foreach (var task in tasks)
+                {
+                    if (task.IsCompleted) this.Invoke(task); // short-circuit the completion action, if possible
+                    else task.AddCompletionAction(this); // simple completion action
+                }
+            }
+
+            public void Invoke(Task ignored)
+            {
+                if (DebuggerSupport.LoggingOn)
+                    DebuggerSupport.TraceOperationRelation(CausalityTraceLevel.Important, this, CausalityRelation.Join);
+
+                // Decrement the count, and only continue to complete the promise if we're the last one.
+                if (Interlocked.Decrement(ref m_count) == 0)
+                {
+                    // Set up some accounting variables
+                    T[] results = new T[m_tasks.Length];
+                    List<ExceptionDispatchInfo> observedExceptions = null;
+                    Task canceledTask = null;
+
+                    // Loop through antecedents:
+                    //   If any one of them faults, the result will be faulted
+                    //   If none fault, but at least one is canceled, the result will be canceled
+                    //   If none fault or are canceled, then result will be RanToCompletion
+                    for (int i = 0; i < m_tasks.Length; i++)
+                    {
+                        Task<T> task = m_tasks[i];
+                        Debug.Assert(task != null, "Constituent task in WhenAll should never be null");
+
+                        if (task.IsFaulted)
+                        {
+                            if (observedExceptions == null) observedExceptions = new List<ExceptionDispatchInfo>();
+                            observedExceptions.AddRange(task.GetExceptionDispatchInfos());
+                        }
+                        else if (task.IsCanceled)
+                        {
+                            if (canceledTask == null) canceledTask = task; // use the first task that's canceled
+                        }
+                        else
+                        {
+                            Debug.Assert(task.Status == TaskStatus.RanToCompletion);
+                            results[i] = task.GetResultCore(waitCompletionNotification: false); // avoid Result, which would triggering debug notification
+                        }
+
+                        // Regardless of completion state, if the task has its debug bit set, transfer it to the
+                        // WhenAll task.  We must do this before we complete the task.
+                        if (task.IsWaitNotificationEnabled) this.SetNotificationForWaitCompletion(enabled: true);
+                        else m_tasks[i] = null; // avoid holding onto tasks unnecessarily
+                    }
+
+                    if (observedExceptions != null)
+                    {
+                        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
+
+                        TrySetException(observedExceptions);
+                    }
+                    else if (canceledTask != null)
+                    {
+                        TrySetCanceled(canceledTask.CancellationToken, canceledTask.GetCancellationExceptionDispatchInfo());
+                    }
+                    else
+                    {
+                        if (DebuggerSupport.LoggingOn)
+                            DebuggerSupport.TraceOperationCompletion(CausalityTraceLevel.Required, this, AsyncStatus.Completed);
+                        DebuggerSupport.RemoveFromActiveTasks(this);
+
+                        TrySetResult(results);
+                    }
+                }
+                Debug.Assert(m_count >= 0, "Count should never go below 0");
+            }
+
+            public bool InvokeMayRunArbitraryCode { get { return true; } }
+
+            /// <summary>
+            /// Returns whether we should notify the debugger of a wait completion.  This returns true
+            /// iff at least one constituent task has its bit set.
+            /// </summary>
+            internal override bool ShouldNotifyDebuggerOfWaitCompletion
+            {
+                get
+                {
+                    return
+                        base.ShouldNotifyDebuggerOfWaitCompletion &&
+                        Task.AnyTaskRequiresNotifyDebuggerOfWaitCompletion(m_tasks);
+                }
+            }
+        }
+        #endregion
+
+        #region WhenAny
+        /// <summary>
+        /// Creates a task that will complete when any of the supplied tasks have completed.
+        /// </summary>
+        /// <param name="tasks">The tasks to wait on for completion.</param>
+        /// <returns>A task that represents the completion of one of the supplied tasks.  The return Task's Result is the task that completed.</returns>
+        /// <remarks>
+        /// The returned task will complete when any of the supplied tasks has completed.  The returned task will always end in the RanToCompletion state 
+        /// with its Result set to the first task to complete.  This is true even if the first task to complete ended in the Canceled or Faulted state.
+        /// </remarks>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="tasks"/> argument was null.
+        /// </exception>
+        /// <exception cref="T:System.ArgumentException">
+        /// The <paramref name="tasks"/> array contained a null task, or was empty.
+        /// </exception>
+        public static Task<Task> WhenAny(params Task[] tasks)
+        {
+            if (tasks == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.tasks);
+            if (tasks.Length == 0)
+            {
+                ThrowHelper.ThrowArgumentException(ExceptionResource.Task_MultiTaskContinuation_EmptyTaskList, ExceptionArgument.tasks);
+            }
+
+            // Make a defensive copy, as the user may manipulate the tasks array
+            // after we return but before the WhenAny asynchronously completes.
+            int taskCount = tasks.Length;
+            Task[] tasksCopy = new Task[taskCount];
+            for (int i = 0; i < taskCount; i++)
+            {
+                Task task = tasks[i];
+                if (task == null) ThrowHelper.ThrowArgumentException(ExceptionResource.Task_MultiTaskContinuation_NullTask, ExceptionArgument.tasks);
+                tasksCopy[i] = task;
+            }
+
+            // Previously implemented CommonCWAnyLogic() can handle the rest
+            return TaskFactory.CommonCWAnyLogic(tasksCopy);
+        }
+
+        /// <summary>
+        /// Creates a task that will complete when any of the supplied tasks have completed.
+        /// </summary>
+        /// <param name="tasks">The tasks to wait on for completion.</param>
+        /// <returns>A task that represents the completion of one of the supplied tasks.  The return Task's Result is the task that completed.</returns>
+        /// <remarks>
+        /// The returned task will complete when any of the supplied tasks has completed.  The returned task will always end in the RanToCompletion state 
+        /// with its Result set to the first task to complete.  This is true even if the first task to complete ended in the Canceled or Faulted state.
+        /// </remarks>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="tasks"/> argument was null.
+        /// </exception>
+        /// <exception cref="T:System.ArgumentException">
+        /// The <paramref name="tasks"/> collection contained a null task, or was empty.
+        /// </exception>
+        public static Task<Task> WhenAny(IEnumerable<Task> tasks)
+        {
+            if (tasks == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.tasks);
+
+            // Make a defensive copy, as the user may manipulate the tasks collection
+            // after we return but before the WhenAny asynchronously completes.
+            List<Task> taskList = new List<Task>();
+            foreach (Task task in tasks)
+            {
+                if (task == null) ThrowHelper.ThrowArgumentException(ExceptionResource.Task_MultiTaskContinuation_NullTask, ExceptionArgument.tasks);
+                taskList.Add(task);
+            }
+
+            if (taskList.Count == 0)
+            {
+                ThrowHelper.ThrowArgumentException(ExceptionResource.Task_MultiTaskContinuation_EmptyTaskList, ExceptionArgument.tasks);
+            }
+
+            // Previously implemented CommonCWAnyLogic() can handle the rest
+            return TaskFactory.CommonCWAnyLogic(taskList);
+        }
+
+        /// <summary>
+        /// Creates a task that will complete when any of the supplied tasks have completed.
+        /// </summary>
+        /// <param name="tasks">The tasks to wait on for completion.</param>
+        /// <returns>A task that represents the completion of one of the supplied tasks.  The return Task's Result is the task that completed.</returns>
+        /// <remarks>
+        /// The returned task will complete when any of the supplied tasks has completed.  The returned task will always end in the RanToCompletion state 
+        /// with its Result set to the first task to complete.  This is true even if the first task to complete ended in the Canceled or Faulted state.
+        /// </remarks>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="tasks"/> argument was null.
+        /// </exception>
+        /// <exception cref="T:System.ArgumentException">
+        /// The <paramref name="tasks"/> array contained a null task, or was empty.
+        /// </exception>
+        public static Task<Task<TResult>> WhenAny<TResult>(params Task<TResult>[] tasks)
+        {
+            // We would just like to do this:
+            //    return (Task<Task<TResult>>) WhenAny( (Task[]) tasks);
+            // but classes are not covariant to enable casting Task<TResult> to Task<Task<TResult>>.
+
+            // Call WhenAny(Task[]) for basic functionality
+            Task<Task> intermediate = WhenAny((Task[])tasks);
+
+            // Return a continuation task with the correct result type
+            return intermediate.ContinueWith(Task<TResult>.TaskWhenAnyCast, default,
+                TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.DenyChildAttach, TaskScheduler.Default);
+        }
+
+        /// <summary>
+        /// Creates a task that will complete when any of the supplied tasks have completed.
+        /// </summary>
+        /// <param name="tasks">The tasks to wait on for completion.</param>
+        /// <returns>A task that represents the completion of one of the supplied tasks.  The return Task's Result is the task that completed.</returns>
+        /// <remarks>
+        /// The returned task will complete when any of the supplied tasks has completed.  The returned task will always end in the RanToCompletion state 
+        /// with its Result set to the first task to complete.  This is true even if the first task to complete ended in the Canceled or Faulted state.
+        /// </remarks>
+        /// <exception cref="T:System.ArgumentNullException">
+        /// The <paramref name="tasks"/> argument was null.
+        /// </exception>
+        /// <exception cref="T:System.ArgumentException">
+        /// The <paramref name="tasks"/> collection contained a null task, or was empty.
+        /// </exception>
+        public static Task<Task<TResult>> WhenAny<TResult>(IEnumerable<Task<TResult>> tasks)
+        {
+            // We would just like to do this:
+            //    return (Task<Task<TResult>>) WhenAny( (IEnumerable<Task>) tasks);
+            // but classes are not covariant to enable casting Task<TResult> to Task<Task<TResult>>.
+
+            // Call WhenAny(IEnumerable<Task>) for basic functionality
+            Task<Task> intermediate = WhenAny((IEnumerable<Task>)tasks);
+
+            // Return a continuation task with the correct result type
+            return intermediate.ContinueWith(Task<TResult>.TaskWhenAnyCast, default,
+                TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.DenyChildAttach, TaskScheduler.Default);
+        }
+        #endregion
+
+        internal static Task<TResult> CreateUnwrapPromise<TResult>(Task outerTask, bool lookForOce)
+        {
+            Debug.Assert(outerTask != null);
+
+            return new UnwrapPromise<TResult>(outerTask, lookForOce);
+        }
+
+        //
+        // This helper routine is targeted by the debugger.
+        //
+//        [DependencyReductionRoot]
+        internal virtual Delegate[] GetDelegateContinuationsForDebugger()
+        {
+            //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 null;
+        }
+
+        private static Delegate[] GetDelegatesFromContinuationObject(object continuationObject)
+        {
+            if (continuationObject != null)
+            {
+                Action singleAction = continuationObject as Action;
+                if (singleAction != null)
+                {
+                    return new Delegate[] { AsyncMethodBuilderCore.TryGetStateMachineForDebugger(singleAction) };
+                }
+
+                TaskContinuation taskContinuation = continuationObject as TaskContinuation;
+                if (taskContinuation != null)
+                {
+                    return taskContinuation.GetDelegateContinuationsForDebugger();
+                }
+
+                Task continuationTask = continuationObject as Task;
+                if (continuationTask != null)
+                {
+                    Debug.Assert(continuationTask.m_action == null);
+                    Delegate[] delegates = continuationTask.GetDelegateContinuationsForDebugger();
+                    if (delegates != null)
+                        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()
+                ITaskCompletionAction singleCompletionAction = continuationObject as ITaskCompletionAction;
+                if (singleCompletionAction != null)
+                {
+                    return new Delegate[] { new Action<Task>(singleCompletionAction.Invoke) };
+                }
+
+                List<object> continuationList = continuationObject as List<object>;
+                if (continuationList != null)
+                {
+                    List<Delegate> result = new List<Delegate>();
+                    foreach (object obj in continuationList)
+                    {
+                        Delegate[] innerDelegates = GetDelegatesFromContinuationObject(obj);
+                        if (innerDelegates != null)
+                        {
+                            foreach (Delegate del in innerDelegates)
+                            {
+                                if (del != null)
+                                    result.Add(del);
+                            }
+                        }
+                    }
+
+                    return result.ToArray();
+                }
+            }
+
+            return null;
+        }
+
+        //
+        // This helper routine is targeted by the debugger.
+        //
+//        [DependencyReductionRoot]
+        private static Task GetActiveTaskFromId(int taskId)
+        {
+            return DebuggerSupport.GetActiveTaskFromId(taskId);
+        }
+    }
+
+    internal sealed class CompletionActionInvoker : IThreadPoolWorkItem
+    {
+        private readonly ITaskCompletionAction m_action;
+        private readonly Task m_completingTask;
+
+        internal CompletionActionInvoker(ITaskCompletionAction action, Task completingTask)
+        {
+            m_action = action;
+            m_completingTask = completingTask;
+        }
+
+        void IThreadPoolWorkItem.Execute()
+        {
+            m_action.Invoke(m_completingTask);
+        }
+    }
+
+    // Proxy class for better debugging experience
+    internal class SystemThreadingTasks_TaskDebugView
+    {
+        private Task m_task;
+
+        public SystemThreadingTasks_TaskDebugView(Task task)
+        {
+            m_task = task;
+        }
+
+        public object AsyncState { get { return m_task.AsyncState; } }
+        public TaskCreationOptions CreationOptions { get { return m_task.CreationOptions; } }
+        public Exception Exception { get { return m_task.Exception; } }
+        public int Id { get { return m_task.Id; } }
+        public bool CancellationPending { get { return (m_task.Status == TaskStatus.WaitingToRun) && m_task.CancellationToken.IsCancellationRequested; } }
+        public TaskStatus Status { get { return m_task.Status; } }
+    }
+
+    /// <summary>
+    /// Specifies flags that control optional behavior for the creation and execution of tasks.
+    /// </summary>
+    // NOTE: These options are a subset of TaskContinuationsOptions, thus before adding a flag check it is
+    // not already in use.
+    [Flags]
+    public enum TaskCreationOptions
+    {
+        /// <summary>
+        /// Specifies that the default behavior should be used.
+        /// </summary>
+        None = 0x0,
+
+        /// <summary>
+        /// A hint to a <see cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see> to schedule a
+        /// task in as fair a manner as possible, meaning that tasks scheduled sooner will be more likely to
+        /// be run sooner, and tasks scheduled later will be more likely to be run later.
+        /// </summary>
+        PreferFairness = 0x01,
+
+        /// <summary>
+        /// Specifies that a task will be a long-running, course-grained operation. It provides a hint to the
+        /// <see cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see> that oversubscription may be
+        /// warranted. 
+        /// </summary>
+        LongRunning = 0x02,
+
+        /// <summary>
+        /// Specifies that a task is attached to a parent in the task hierarchy.
+        /// </summary>
+        AttachedToParent = 0x04,
+
+        /// <summary>
+        /// Specifies that an InvalidOperationException will be thrown if an attempt is made to attach a child task to the created task.
+        /// </summary>
+        DenyChildAttach = 0x08,
+
+        /// <summary>
+        /// Prevents the ambient scheduler from being seen as the current scheduler in the created task.  This means that operations
+        /// like StartNew or ContinueWith that are performed in the created task will see TaskScheduler.Default as the current scheduler.
+        /// </summary>
+        HideScheduler = 0x10,
+
+        // 0x20 is already being used in TaskContinuationOptions
+
+        /// <summary>
+        /// Forces continuations added to the current task to be executed asynchronously.
+        /// This option has precedence over TaskContinuationOptions.ExecuteSynchronously
+        /// </summary>
+        RunContinuationsAsynchronously = 0x40
+    }
+
+
+    /// <summary>
+    /// Task creation flags which are only used internally.
+    /// </summary>
+    [Flags]
+    internal enum InternalTaskOptions
+    {
+        /// <summary> Specifies "No internal task options" </summary>
+        None,
+
+        /// <summary>Used to filter out internal vs. public task creation options.</summary>
+        InternalOptionsMask = 0x0000FF00,
+
+        ContinuationTask = 0x0200,
+        PromiseTask = 0x0400,
+
+        /// <summary>
+        /// Store the presence of TaskContinuationOptions.LazyCancellation, since it does not directly
+        /// translate into any TaskCreationOptions.
+        /// </summary>
+        LazyCancellation = 0x1000,
+
+        /// <summary>Specifies that the task will be queued by the runtime before handing it over to the user. 
+        /// This flag will be used to skip the cancellationtoken registration step, which is only meant for unstarted tasks.</summary>
+        QueuedByRuntime = 0x2000,
+
+        /// <summary>
+        /// Denotes that Dispose should be a complete nop for a Task.  Used when constructing tasks that are meant to be cached/reused.
+        /// </summary>
+        DoNotDispose = 0x4000
+    }
+
+    /// <summary>
+    /// Specifies flags that control optional behavior for the creation and execution of continuation tasks.
+    /// </summary>
+    [Flags]
+    public enum TaskContinuationOptions
+    {
+        /// <summary>
+        /// Default = "Continue on any, no task options, run asynchronously"
+        /// Specifies that the default behavior should be used.  Continuations, by default, will
+        /// be scheduled when the antecedent task completes, regardless of the task's final <see
+        /// cref="System.Threading.Tasks.TaskStatus">TaskStatus</see>.
+        /// </summary>
+        None = 0,
+
+        // These are identical to their meanings and values in TaskCreationOptions
+
+        /// <summary>
+        /// A hint to a <see cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see> to schedule a
+        /// task in as fair a manner as possible, meaning that tasks scheduled sooner will be more likely to
+        /// be run sooner, and tasks scheduled later will be more likely to be run later.
+        /// </summary>
+        PreferFairness = 0x01,
+
+        /// <summary>
+        /// Specifies that a task will be a long-running, course-grained operation.  It provides
+        /// a hint to the <see cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see> that
+        /// oversubscription may be warranted.
+        /// </summary>
+        LongRunning = 0x02,
+        /// <summary>
+        /// Specifies that a task is attached to a parent in the task hierarchy.
+        /// </summary>
+        AttachedToParent = 0x04,
+
+        /// <summary>
+        /// Specifies that an InvalidOperationException will be thrown if an attempt is made to attach a child task to the created task.
+        /// </summary>
+        DenyChildAttach = 0x08,
+        /// <summary>
+        /// Prevents the ambient scheduler from being seen as the current scheduler in the created task.  This means that operations
+        /// like StartNew or ContinueWith that are performed in the created task will see TaskScheduler.Default as the current scheduler.
+        /// </summary>
+        HideScheduler = 0x10,
+
+        /// <summary>
+        /// In the case of continuation cancellation, prevents completion of the continuation until the antecedent has completed.
+        /// </summary>
+        LazyCancellation = 0x20,
+
+        RunContinuationsAsynchronously = 0x40,
+
+        // These are specific to continuations
+
+        /// <summary>
+        /// Specifies that the continuation task should not be scheduled if its antecedent ran to completion.
+        /// This option is not valid for multi-task continuations.
+        /// </summary>
+        NotOnRanToCompletion = 0x10000,
+        /// <summary>
+        /// Specifies that the continuation task should not be scheduled if its antecedent threw an unhandled
+        /// exception. This option is not valid for multi-task continuations.
+        /// </summary>
+        NotOnFaulted = 0x20000,
+        /// <summary>
+        /// Specifies that the continuation task should not be scheduled if its antecedent was canceled. This
+        /// option is not valid for multi-task continuations.
+        /// </summary>
+        NotOnCanceled = 0x40000,
+        /// <summary>
+        /// Specifies that the continuation task should be scheduled only if its antecedent ran to
+        /// completion. This option is not valid for multi-task continuations.
+        /// </summary>
+        OnlyOnRanToCompletion = NotOnFaulted | NotOnCanceled,
+        /// <summary>
+        /// Specifies that the continuation task should be scheduled only if its antecedent threw an
+        /// unhandled exception. This option is not valid for multi-task continuations.
+        /// </summary>
+        OnlyOnFaulted = NotOnRanToCompletion | NotOnCanceled,
+        /// <summary>
+        /// Specifies that the continuation task should be scheduled only if its antecedent was canceled.
+        /// This option is not valid for multi-task continuations.
+        /// </summary>
+        OnlyOnCanceled = NotOnRanToCompletion | NotOnFaulted,
+        /// <summary>
+        /// Specifies that the continuation task should be executed synchronously. With this option
+        /// specified, the continuation will be run on the same thread that causes the antecedent task to
+        /// transition into its final state. If the antecedent is already complete when the continuation is
+        /// created, the continuation will run on the thread creating the continuation.  Only very
+        /// short-running continuations should be executed synchronously.
+        /// </summary>
+        ExecuteSynchronously = 0x80000
+    }
+
+    /// <summary>
+    /// Internal helper class to keep track of stack depth and decide whether we should inline or not.
+    /// </summary>
+    internal class StackGuard
+    {
+        // current thread's depth of nested inline task executions
+        private int m_inliningDepth = 0;
+
+        // For relatively small inlining depths we don't want to get into the business of stack probing etc.
+        // This clearly leaves a window of opportunity for the user code to SO. However a piece of code
+        // that can SO in 20 inlines on a typical 1MB stack size probably needs to be revisited anyway.
+        private const int MAX_UNCHECKED_INLINING_DEPTH = 20;
+
+        /// <summary>
+        /// This method needs to be called before attempting inline execution on the current thread. 
+        /// If false is returned, it means we are too close to the end of the stack and should give up inlining.
+        /// Each call to TryBeginInliningScope() that returns true must be matched with a 
+        /// call to EndInliningScope() regardless of whether inlining actually took place.
+        /// </summary>
+        internal bool TryBeginInliningScope()
+        {
+            // If we're still under the 'safe' limit we'll just skip the stack probe to save p/invoke calls
+            if (m_inliningDepth < MAX_UNCHECKED_INLINING_DEPTH || RuntimeHelpers.TryEnsureSufficientExecutionStack())
+            {
+                m_inliningDepth++;
+                return true;
+            }
+            else
+                return false;
+        }
+
+        /// <summary>
+        /// This needs to be called once for each previous successful TryBeginInliningScope() call after
+        /// inlining related logic runs.
+        /// </summary>
+        internal void EndInliningScope()
+        {
+            m_inliningDepth--;
+            Debug.Assert(m_inliningDepth >= 0, "Inlining depth count should never go negative.");
+
+            // do the right thing just in case...
+            if (m_inliningDepth < 0) m_inliningDepth = 0;
+        }
+    }
+
+    // Special internal struct that we use to signify that we are not interested in
+    // a Task<VoidTaskResult>'s result.
+    internal struct VoidTaskResult { }
+
+    // Interface to which all completion actions must conform.
+    // This interface allows us to combine functionality and reduce allocations.
+    // For example, see Task.SetOnInvokeMres, and its use in Task.SpinThenBlockingWait().
+    // This code:
+    //      ManualResetEvent mres = new ManualResetEventSlim(false, 0);
+    //      Action<Task> completionAction = delegate { mres.Set() ; };
+    //      AddCompletionAction(completionAction);
+    // gets replaced with this:
+    //      SetOnInvokeMres mres = new SetOnInvokeMres();
+    //      AddCompletionAction(mres);
+    // For additional examples of where this is used, see internal classes Task.SignalOnInvokeCDE,
+    // Task.WhenAllPromise, Task.WhenAllPromise<T>, TaskFactory.CompleteOnCountdownPromise,
+    // TaskFactory.CompleteOnCountdownPromise<T>, and TaskFactory.CompleteOnInvokePromise.
+    internal interface ITaskCompletionAction
+    {
+        /// <summary>Invoked to run the completion action.</summary>
+        void Invoke(Task completingTask);
+
+        /// <summary>
+        /// Some completion actions are considered internal implementation details of tasks,
+        /// using the continuation mechanism only for performance reasons.  Such actions perform
+        /// known quantities and types of work, and can be invoked safely as a continuation even
+        /// if the system wants to prevent arbitrary continuations from running synchronously.
+        /// This should only return false for a limited set of implementations where a small amount
+        /// of work is guaranteed to be performed, e.g. setting a ManualResetEventSlim.
+        /// </summary>
+        bool InvokeMayRunArbitraryCode { get; }
+    }
+
+    // This class encapsulates all "unwrap" logic, and also implements ITaskCompletionAction,
+    // which minimizes the allocations needed for queuing it to its antecedent.  This
+    // logic is used by both the Unwrap extension methods and the unwrap-style Task.Run methods.
+    internal sealed class UnwrapPromise<TResult> : Task<TResult>, ITaskCompletionAction
+    {
+        // The possible states for our UnwrapPromise, used by Invoke() to determine which logic to execute
+        private const byte STATE_WAITING_ON_OUTER_TASK = 0; // Invoke() means "process completed outer task"
+        private const byte STATE_WAITING_ON_INNER_TASK = 1; // Invoke() means "process completed inner task"
+        private const byte STATE_DONE = 2;                  // Invoke() means "something went wrong and we are hosed!"
+
+        // Keep track of our state; initialized to STATE_WAITING_ON_OUTER_TASK in the constructor
+        private byte _state;
+
+        // "Should we check for OperationCanceledExceptions on the outer task and interpret them as proxy cancellation?"
+        // Unwrap() sets this to false, Run() sets it to true.
+        private readonly bool _lookForOce;
+
+        public UnwrapPromise(Task outerTask, bool lookForOce)
+            : base((object)null, outerTask.CreationOptions & TaskCreationOptions.AttachedToParent)
+        {
+            Debug.Assert(outerTask != null, "Expected non-null outerTask");
+            _lookForOce = lookForOce;
+            _state = STATE_WAITING_ON_OUTER_TASK;
+
+            if (DebuggerSupport.LoggingOn)
+                DebuggerSupport.TraceOperationCreation(CausalityTraceLevel.Required, this, "Task.Unwrap", 0);
+            DebuggerSupport.AddToActiveTasks(this);
+
+            // Link ourselves to the outer task.
+            // If the outer task has already completed, take the fast path
+            // of immediately transferring its results or processing the inner task.
+            if (outerTask.IsCompleted)
+            {
+                ProcessCompletedOuterTask(outerTask);
+            }
+            else // Otherwise, process its completion asynchronously.
+            {
+                outerTask.AddCompletionAction(this);
+            }
+        }
+
+        // For ITaskCompletionAction 
+        public void Invoke(Task completingTask)
+        {
+            // Check the current stack guard.  If we're ok to inline,
+            // process the task, and reset the guard when we're done.
+            var sg = Task.CurrentStackGuard;
+            if (sg.TryBeginInliningScope())
+            {
+                try { InvokeCore(completingTask); }
+                finally { sg.EndInliningScope(); }
+            }
+            // Otherwise, we're too deep on the stack, and
+            // we shouldn't run the continuation chain here, so queue a work
+            // item to call back here to Invoke asynchronously.
+            else InvokeCoreAsync(completingTask);
+        }
+
+        /// <summary>
+        /// Processes the completed task. InvokeCore could be called twice:
+        /// once for the outer task, once for the inner task.
+        /// </summary>
+        /// <param name="completingTask">The completing outer or inner task.</param>
+        private void InvokeCore(Task completingTask)
+        {
+            switch (_state)
+            {
+                case STATE_WAITING_ON_OUTER_TASK:
+                    ProcessCompletedOuterTask(completingTask);
+                    // We bump the state inside of ProcessCompletedOuterTask because it can also be called from the constructor.
+                    break;
+                case STATE_WAITING_ON_INNER_TASK:
+                    bool result = TrySetFromTask(completingTask, lookForOce: false);
+                    _state = STATE_DONE; // bump the state
+                    Debug.Assert(result, "Expected TrySetFromTask from inner task to succeed");
+                    break;
+                default:
+                    Debug.Fail("UnwrapPromise in illegal state");
+                    break;
+            }
+        }
+
+        // Calls InvokeCore asynchronously.
+        private void InvokeCoreAsync(Task completingTask)
+        {
+            // Queue a call to Invoke.  If we're so deep on the stack that we're at risk of overflowing,
+            // there's a high liklihood this thread is going to be doing lots more work before
+            // returning to the thread pool (at the very least unwinding through thousands of
+            // stack frames).  So we queue to the global queue.
+            ThreadPool.UnsafeQueueUserWorkItem(state =>
+            {
+                // InvokeCore(completingTask);
+                var tuple = (Tuple<UnwrapPromise<TResult>, Task>)state;
+                tuple.Item1.InvokeCore(tuple.Item2);
+            }, Tuple.Create<UnwrapPromise<TResult>, Task>(this, completingTask));
+        }
+
+        /// <summary>Processes the outer task once it's completed.</summary>
+        /// <param name="task">The now-completed outer task.</param>
+        private void ProcessCompletedOuterTask(Task task)
+        {
+            Debug.Assert(task != null && task.IsCompleted, "Expected non-null, completed outer task");
+            Debug.Assert(_state == STATE_WAITING_ON_OUTER_TASK, "We're in the wrong state!");
+
+            // Bump our state before proceeding any further
+            _state = STATE_WAITING_ON_INNER_TASK;
+
+            switch (task.Status)
+            {
+                // If the outer task did not complete successfully, then record the 
+                // cancellation/fault information to tcs.Task.
+                case TaskStatus.Canceled:
+                case TaskStatus.Faulted:
+                    bool result = TrySetFromTask(task, _lookForOce);
+                    Debug.Assert(result, "Expected TrySetFromTask from outer task to succeed");
+                    break;
+
+                // Otherwise, process the inner task it returned.
+                case TaskStatus.RanToCompletion:
+                    var taskOfTaskOfTResult = task as Task<Task<TResult>>; // it's either a Task<Task> or Task<Task<TResult>>
+                    ProcessInnerTask(taskOfTaskOfTResult != null ?
+                        taskOfTaskOfTResult.Result : ((Task<Task>)task).Result);
+                    break;
+            }
+        }
+
+        /// <summary>Transfer the completion status from "task" to ourself.</summary>
+        /// <param name="task">The source task whose results should be transfered to <paramref name="promise"/>.</param>
+        /// <param name="lookForOce">Whether or not to look for OperationCanceledExceptions in task's exceptions if it faults.</param>
+        /// <returns>true if the transfer was successful; otherwise, false.</returns>
+        private bool TrySetFromTask(Task task, bool lookForOce)
+        {
+            Debug.Assert(task != null && task.IsCompleted, "TrySetFromTask: Expected task to have completed.");
+
+            if (DebuggerSupport.LoggingOn)
+                DebuggerSupport.TraceOperationRelation(CausalityTraceLevel.Important, this, CausalityRelation.Join);
+
+            bool result = false;
+            switch (task.Status)
+            {
+                case TaskStatus.Canceled:
+                    result = TrySetCanceled(task.CancellationToken, task.GetCancellationExceptionDispatchInfo());
+                    break;
+
+                case TaskStatus.Faulted:
+                    var edis = task.GetExceptionDispatchInfos();
+                    ExceptionDispatchInfo oceEdi;
+                    OperationCanceledException oce;
+                    if (lookForOce && edis.Count > 0 &&
+                        (oceEdi = edis[0]) != null &&
+                        (oce = oceEdi.SourceException as OperationCanceledException) != null)
+                    {
+                        result = TrySetCanceled(oce.CancellationToken, oceEdi);
+                    }
+                    else
+                    {
+                        result = TrySetException(edis);
+                    }
+                    break;
+
+                case TaskStatus.RanToCompletion:
+                    var taskTResult = task as Task<TResult>;
+
+                    if (DebuggerSupport.LoggingOn)
+                        DebuggerSupport.TraceOperationCompletion(CausalityTraceLevel.Required, this, AsyncStatus.Completed);
+                    DebuggerSupport.RemoveFromActiveTasks(this);
+
+                    result = TrySetResult(taskTResult != null ? taskTResult.Result : default);
+                    break;
+            }
+            return result;
+        }
+
+        /// <summary>
+        /// Processes the inner task of a Task{Task} or Task{Task{TResult}}, 
+        /// transferring the appropriate results to ourself.
+        /// </summary>
+        /// <param name="task">The inner task returned by the task provided by the user.</param>
+        private void ProcessInnerTask(Task task)
+        {
+            // If the inner task is null, the proxy should be canceled.
+            if (task == null)
+            {
+                TrySetCanceled(default);
+                _state = STATE_DONE; // ... and record that we are done
+            }
+
+            // Fast path for if the inner task is already completed
+            else if (task.IsCompleted)
+            {
+                TrySetFromTask(task, lookForOce: false);
+                _state = STATE_DONE; // ... and record that we are done
+            }
+
+            // The inner task exists but is not yet complete, so when it does complete,
+            // take some action to set our completion state.
+            else
+            {
+                task.AddCompletionAction(this);
+                // We'll record that we are done when Invoke() is called.
+            }
+        }
+
+        public bool InvokeMayRunArbitraryCode { get { return true; } }
+    }
+}

+ 781 - 0
mcs/class/System.Private.CoreLib/temp/TaskContinuation.cs

@@ -0,0 +1,781 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
+//
+//
+//
+// Implementation of task continuations, TaskContinuation, and its descendants.
+//
+// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
+
+using System.Security;
+using System.Diagnostics;
+using System.Runtime.ExceptionServices;
+using System.Runtime.CompilerServices;
+
+using Internal.Runtime.Augments;
+
+using AsyncStatus = Internal.Runtime.Augments.AsyncStatus;
+using CausalityRelation = Internal.Runtime.Augments.CausalityRelation;
+using CausalitySource = Internal.Runtime.Augments.CausalitySource;
+using CausalityTraceLevel = Internal.Runtime.Augments.CausalityTraceLevel;
+using CausalitySynchronousWork = Internal.Runtime.Augments.CausalitySynchronousWork;
+
+namespace System.Threading.Tasks
+{
+    // Task type used to implement: Task ContinueWith(Action<Task,...>)
+    internal sealed class ContinuationTaskFromTask : Task
+    {
+        private Task m_antecedent;
+
+        public ContinuationTaskFromTask(
+            Task antecedent, Delegate action, object state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions) :
+            base(action, state, Task.InternalCurrentIfAttached(creationOptions), default, creationOptions, internalOptions, null)
+        {
+            Debug.Assert(action is Action<Task> || action is Action<Task, object>,
+                "Invalid delegate type in ContinuationTaskFromTask");
+            m_antecedent = antecedent;
+        }
+
+        /// <summary>
+        /// Evaluates the value selector of the Task which is passed in as an object and stores the result.
+        /// </summary>        
+        internal override void InnerInvoke()
+        {
+            // Get and null out the antecedent.  This is crucial to avoid a memory
+            // leak with long chains of continuations.
+            var antecedent = m_antecedent;
+            Debug.Assert(antecedent != null,
+                "No antecedent was set for the ContinuationTaskFromTask.");
+            m_antecedent = null;
+
+            // Notify the debugger we're completing an asynchronous wait on a task
+            antecedent.NotifyDebuggerOfWaitCompletionIfNecessary();
+
+            // Invoke the delegate
+            Debug.Assert(m_action != null);
+            var action = m_action as Action<Task>;
+            if (action != null)
+            {
+                action(antecedent);
+                return;
+            }
+            var actionWithState = m_action as Action<Task, object>;
+            if (actionWithState != null)
+            {
+                actionWithState(antecedent, m_stateObject);
+                return;
+            }
+            Debug.Fail("Invalid m_action in ContinuationTaskFromTask");
+        }
+    }
+
+    // Task type used to implement: Task<TResult> ContinueWith(Func<Task,...>)
+    internal sealed class ContinuationResultTaskFromTask<TResult> : Task<TResult>
+    {
+        private Task m_antecedent;
+
+        public ContinuationResultTaskFromTask(
+            Task antecedent, Delegate function, object state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions) :
+            base(function, state, Task.InternalCurrentIfAttached(creationOptions), default, creationOptions, internalOptions, null)
+        {
+            Debug.Assert(function is Func<Task, TResult> || function is Func<Task, object, TResult>,
+                "Invalid delegate type in ContinuationResultTaskFromTask");
+            m_antecedent = antecedent;
+        }
+
+        /// <summary>
+        /// Evaluates the value selector of the Task which is passed in as an object and stores the result.
+        /// </summary>        
+        internal override void InnerInvoke()
+        {
+            // Get and null out the antecedent.  This is crucial to avoid a memory
+            // leak with long chains of continuations.
+            var antecedent = m_antecedent;
+            Debug.Assert(antecedent != null,
+                "No antecedent was set for the ContinuationResultTaskFromTask.");
+            m_antecedent = null;
+
+            // Notify the debugger we're completing an asynchronous wait on a task
+            antecedent.NotifyDebuggerOfWaitCompletionIfNecessary();
+
+            // Invoke the delegate
+            Debug.Assert(m_action != null);
+            var func = m_action as Func<Task, TResult>;
+            if (func != null)
+            {
+                m_result = func(antecedent);
+                return;
+            }
+            var funcWithState = m_action as Func<Task, object, TResult>;
+            if (funcWithState != null)
+            {
+                m_result = funcWithState(antecedent, m_stateObject);
+                return;
+            }
+            Debug.Fail("Invalid m_action in ContinuationResultTaskFromTask");
+        }
+    }
+
+    // Task type used to implement: Task ContinueWith(Action<Task<TAntecedentResult>,...>)
+    internal sealed class ContinuationTaskFromResultTask<TAntecedentResult> : Task
+    {
+        private Task<TAntecedentResult> m_antecedent;
+
+        public ContinuationTaskFromResultTask(
+            Task<TAntecedentResult> antecedent, Delegate action, object state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions) :
+            base(action, state, Task.InternalCurrentIfAttached(creationOptions), default, creationOptions, internalOptions, null)
+        {
+            Debug.Assert(action is Action<Task<TAntecedentResult>> || action is Action<Task<TAntecedentResult>, object>,
+                "Invalid delegate type in ContinuationTaskFromResultTask");
+            m_antecedent = antecedent;
+        }
+
+        /// <summary>
+        /// Evaluates the value selector of the Task which is passed in as an object and stores the result.
+        /// </summary>
+        internal override void InnerInvoke()
+        {
+            // Get and null out the antecedent.  This is crucial to avoid a memory
+            // leak with long chains of continuations.
+            var antecedent = m_antecedent;
+            Debug.Assert(antecedent != null,
+                "No antecedent was set for the ContinuationTaskFromResultTask.");
+            m_antecedent = null;
+
+            // Notify the debugger we're completing an asynchronous wait on a task
+            antecedent.NotifyDebuggerOfWaitCompletionIfNecessary();
+
+            // Invoke the delegate
+            Debug.Assert(m_action != null);
+            var action = m_action as Action<Task<TAntecedentResult>>;
+            if (action != null)
+            {
+                action(antecedent);
+                return;
+            }
+            var actionWithState = m_action as Action<Task<TAntecedentResult>, object>;
+            if (actionWithState != null)
+            {
+                actionWithState(antecedent, m_stateObject);
+                return;
+            }
+            Debug.Fail("Invalid m_action in ContinuationTaskFromResultTask");
+        }
+    }
+
+    // Task type used to implement: Task<TResult> ContinueWith(Func<Task<TAntecedentResult>,...>)
+    internal sealed class ContinuationResultTaskFromResultTask<TAntecedentResult, TResult> : Task<TResult>
+    {
+        private Task<TAntecedentResult> m_antecedent;
+
+        public ContinuationResultTaskFromResultTask(
+            Task<TAntecedentResult> antecedent, Delegate function, object state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions) :
+            base(function, state, Task.InternalCurrentIfAttached(creationOptions), default, creationOptions, internalOptions, null)
+        {
+            Debug.Assert(function is Func<Task<TAntecedentResult>, TResult> || function is Func<Task<TAntecedentResult>, object, TResult>,
+                "Invalid delegate type in ContinuationResultTaskFromResultTask");
+            m_antecedent = antecedent;
+        }
+
+        /// <summary>
+        /// Evaluates the value selector of the Task which is passed in as an object and stores the result.
+        /// </summary>
+        internal override void InnerInvoke()
+        {
+            // Get and null out the antecedent.  This is crucial to avoid a memory
+            // leak with long chains of continuations.
+            var antecedent = m_antecedent;
+            Debug.Assert(antecedent != null,
+                "No antecedent was set for the ContinuationResultTaskFromResultTask.");
+            m_antecedent = null;
+
+            // Notify the debugger we're completing an asynchronous wait on a task
+            antecedent.NotifyDebuggerOfWaitCompletionIfNecessary();
+
+            // Invoke the delegate
+            Debug.Assert(m_action != null);
+            var func = m_action as Func<Task<TAntecedentResult>, TResult>;
+            if (func != null)
+            {
+                m_result = func(antecedent);
+                return;
+            }
+            var funcWithState = m_action as Func<Task<TAntecedentResult>, object, TResult>;
+            if (funcWithState != null)
+            {
+                m_result = funcWithState(antecedent, m_stateObject);
+                return;
+            }
+            Debug.Fail("Invalid m_action in ContinuationResultTaskFromResultTask");
+        }
+    }
+
+    // For performance reasons, we don't just have a single way of representing
+    // a continuation object.  Rather, we have a hierarchy of types:
+    // - TaskContinuation: abstract base that provides a virtual Run method
+    //     - StandardTaskContinuation: wraps a task,options,and scheduler, and overrides Run to process the task with that configuration
+    //     - AwaitTaskContinuation: base for continuations created through TaskAwaiter; targets default scheduler by default
+    //         - TaskSchedulerAwaitTaskContinuation: awaiting with a non-default TaskScheduler
+    //         - SynchronizationContextAwaitTaskContinuation: awaiting with a "current" sync ctx
+
+    /// <summary>Represents a continuation.</summary>
+    internal abstract class TaskContinuation
+    {
+        /// <summary>Inlines or schedules the continuation.</summary>
+        /// <param name="completedTask">The antecedent task that has completed.</param>
+        /// <param name="canInlineContinuationTask">true if inlining is permitted; otherwise, false.</param>
+        internal abstract void Run(Task completedTask, bool canInlineContinuationTask);
+
+        /// <summary>Tries to run the task on the current thread, if possible; otherwise, schedules it.</summary>
+        /// <param name="task">The task to run</param>
+        /// <param name="needsProtection">
+        /// true if we need to protect against multiple threads racing to start/cancel the task; otherwise, false.
+        /// </param>
+        protected static void InlineIfPossibleOrElseQueue(Task task, bool needsProtection)
+        {
+            Debug.Assert(task != null);
+            Debug.Assert(task.m_taskScheduler != null);
+
+            // Set the TASK_STATE_STARTED flag.  This only needs to be done
+            // if the task may be canceled or if someone else has a reference to it
+            // that may try to execute it.
+            if (needsProtection)
+            {
+                if (!task.MarkStarted())
+                    return; // task has been previously started or canceled.  Stop processing.
+            }
+            else
+            {
+                task.m_stateFlags |= Task.TASK_STATE_STARTED;
+            }
+
+            // Try to inline it but queue if we can't
+            try
+            {
+                if (!task.m_taskScheduler.TryRunInline(task, taskWasPreviouslyQueued: false))
+                {
+                    task.m_taskScheduler.InternalQueueTask(task);
+                }
+            }
+            catch (Exception e)
+            {
+                // Either TryRunInline() or QueueTask() threw an exception. Record the exception, marking the task as Faulted.
+                // However if it was a ThreadAbortException coming from TryRunInline we need to skip here, 
+                // because it would already have been handled in Task.Execute()
+                //if (!(e is ThreadAbortException && 
+                //      (task.m_stateFlags & Task.TASK_STATE_THREAD_WAS_ABORTED) != 0))    // this ensures TAEs from QueueTask will be wrapped in TSE
+                {
+                    TaskSchedulerException tse = new TaskSchedulerException(e);
+                    task.AddException(tse);
+                    task.Finish(false);
+                }
+                // Don't re-throw.
+            }
+        }
+
+        //
+        // This helper routine is targeted by the debugger.
+        //
+#if PROJECTN
+        [DependencyReductionRoot]
+#endif
+        internal abstract Delegate[] GetDelegateContinuationsForDebugger();
+    }
+
+    /// <summary>Provides the standard implementation of a task continuation.</summary>
+    internal class StandardTaskContinuation : TaskContinuation
+    {
+        /// <summary>The unstarted continuation task.</summary>
+        internal readonly Task m_task;
+        /// <summary>The options to use with the continuation task.</summary>
+        internal readonly TaskContinuationOptions m_options;
+        /// <summary>The task scheduler with which to run the continuation task.</summary>
+        private readonly TaskScheduler m_taskScheduler;
+
+        /// <summary>Initializes a new continuation.</summary>
+        /// <param name="task">The task to be activated.</param>
+        /// <param name="options">The continuation options.</param>
+        /// <param name="scheduler">The scheduler to use for the continuation.</param>
+        internal StandardTaskContinuation(Task task, TaskContinuationOptions options, TaskScheduler scheduler)
+        {
+            Debug.Assert(task != null, "TaskContinuation ctor: task is null");
+            Debug.Assert(scheduler != null, "TaskContinuation ctor: scheduler is null");
+            m_task = task;
+            m_options = options;
+            m_taskScheduler = scheduler;
+
+            if (DebuggerSupport.LoggingOn)
+                DebuggerSupport.TraceOperationCreation(CausalityTraceLevel.Required, m_task, "Task.ContinueWith: " + task.m_action, 0);
+            DebuggerSupport.AddToActiveTasks(m_task);
+        }
+
+        /// <summary>Invokes the continuation for the target completion task.</summary>
+        /// <param name="completedTask">The completed task.</param>
+        /// <param name="canInlineContinuationTask">Whether the continuation can be inlined.</param>
+        internal override void Run(Task completedTask, bool canInlineContinuationTask)
+        {
+            Debug.Assert(completedTask != null);
+            Debug.Assert(completedTask.IsCompleted, "ContinuationTask.Run(): completedTask not completed");
+
+            // Check if the completion status of the task works with the desired 
+            // activation criteria of the TaskContinuationOptions.
+            TaskContinuationOptions options = m_options;
+            bool isRightKind =
+                completedTask.IsCompletedSuccessfully ?
+                    (options & TaskContinuationOptions.NotOnRanToCompletion) == 0 :
+                    (completedTask.IsCanceled ?
+                        (options & TaskContinuationOptions.NotOnCanceled) == 0 :
+                        (options & TaskContinuationOptions.NotOnFaulted) == 0);
+
+            // If the completion status is allowed, run the continuation.
+            Task continuationTask = m_task;
+            if (isRightKind)
+            {
+                if (!continuationTask.IsCanceled && DebuggerSupport.LoggingOn)
+                {
+                    // Log now that we are sure that this continuation is being ran
+                    DebuggerSupport.TraceOperationRelation(CausalityTraceLevel.Important, continuationTask, CausalityRelation.AssignDelegate);
+                }
+                continuationTask.m_taskScheduler = m_taskScheduler;
+
+                // Either run directly or just queue it up for execution, depending
+                // on whether synchronous or asynchronous execution is wanted.
+                if (canInlineContinuationTask && // inlining is allowed by the caller
+                    (options & TaskContinuationOptions.ExecuteSynchronously) != 0) // synchronous execution was requested by the continuation's creator
+                {
+                    InlineIfPossibleOrElseQueue(continuationTask, needsProtection: true);
+                }
+                else
+                {
+                    try { continuationTask.ScheduleAndStart(needsProtection: true); }
+                    catch (TaskSchedulerException)
+                    {
+                        // No further action is necessary -- ScheduleAndStart() already transitioned the 
+                        // task to faulted.  But we want to make sure that no exception is thrown from here.
+                    }
+                }
+            }
+            // Otherwise, the final state of this task does not match the desired
+            // continuation activation criteria; cancel it to denote this.
+            else continuationTask.InternalCancel(false);
+        }
+
+        internal override Delegate[] GetDelegateContinuationsForDebugger()
+        {
+            if (m_task.m_action == null)
+            {
+                return m_task.GetDelegateContinuationsForDebugger();
+            }
+
+            return new Delegate[] { m_task.m_action };
+        }
+    }
+
+    /// <summary>Task continuation for awaiting with a current synchronization context.</summary>
+    internal sealed class SynchronizationContextAwaitTaskContinuation : AwaitTaskContinuation
+    {
+        /// <summary>SendOrPostCallback delegate to invoke the action.</summary>
+        private static readonly SendOrPostCallback s_postCallback = state => ((Action)state)(); // can't use InvokeAction as it's SecurityCritical
+        /// <summary>Cached delegate for PostAction</summary>
+        private static ContextCallback s_postActionCallback;
+        /// <summary>The context with which to run the action.</summary>
+        private readonly SynchronizationContext m_syncContext;
+
+        /// <summary>Initializes the SynchronizationContextAwaitTaskContinuation.</summary>
+        /// <param name="context">The synchronization context with which to invoke the action.  Must not be null.</param>
+        /// <param name="action">The action to invoke. Must not be null.</param>
+        /// <param name="flowExecutionContext">Whether to capture and restore ExecutionContext.</param>
+        internal SynchronizationContextAwaitTaskContinuation(
+            SynchronizationContext context, Action action, bool flowExecutionContext) :
+            base(action, flowExecutionContext)
+        {
+            Debug.Assert(context != null);
+            m_syncContext = context;
+        }
+
+        /// <summary>Inlines or schedules the continuation.</summary>
+        /// <param name="task">The antecedent task, which is ignored.</param>
+        /// <param name="canInlineContinuationTask">true if inlining is permitted; otherwise, false.</param>
+        internal sealed override void Run(Task task, bool canInlineContinuationTask)
+        {
+            // If we're allowed to inline, run the action on this thread.
+            if (canInlineContinuationTask &&
+                m_syncContext == SynchronizationContext.Current)
+            {
+                RunCallback(GetInvokeActionCallback(), m_action, ref Task.t_currentTask);
+            }
+            // Otherwise, Post the action back to the SynchronizationContext.
+            else
+            {
+                RunCallback(GetPostActionCallback(), this, ref Task.t_currentTask);
+            }
+            // Any exceptions will be handled by RunCallback.
+        }
+
+        /// <summary>Calls InvokeOrPostAction(false) on the supplied SynchronizationContextAwaitTaskContinuation.</summary>
+        /// <param name="state">The SynchronizationContextAwaitTaskContinuation.</param>
+        private static void PostAction(object state)
+        {
+            var c = (SynchronizationContextAwaitTaskContinuation)state;
+
+            c.m_syncContext.Post(s_postCallback, c.m_action); // s_postCallback is manually cached, as the compiler won't in a SecurityCritical method
+        }
+
+        /// <summary>Gets a cached delegate for the PostAction method.</summary>
+        /// <returns>
+        /// A delegate for PostAction, which expects a SynchronizationContextAwaitTaskContinuation 
+        /// to be passed as state.
+        /// </returns>
+        [MethodImpl(MethodImplOptions.AggressiveInlining)]
+        private static ContextCallback GetPostActionCallback()
+        {
+            ContextCallback callback = s_postActionCallback;
+            if (callback == null) { s_postActionCallback = callback = PostAction; } // lazily initialize SecurityCritical delegate
+            return callback;
+        }
+    }
+
+    /// <summary>Task continuation for awaiting with a task scheduler.</summary>
+    internal sealed class TaskSchedulerAwaitTaskContinuation : AwaitTaskContinuation
+    {
+        /// <summary>The scheduler on which to run the action.</summary>
+        private readonly TaskScheduler m_scheduler;
+
+        /// <summary>Initializes the TaskSchedulerAwaitTaskContinuation.</summary>
+        /// <param name="scheduler">The task scheduler with which to invoke the action.  Must not be null.</param>
+        /// <param name="action">The action to invoke. Must not be null.</param>
+        /// <param name="flowExecutionContext">Whether to capture and restore ExecutionContext.</param>
+        internal TaskSchedulerAwaitTaskContinuation(
+            TaskScheduler scheduler, Action action, bool flowExecutionContext) :
+            base(action, flowExecutionContext)
+        {
+            Debug.Assert(scheduler != null);
+            m_scheduler = scheduler;
+        }
+
+        /// <summary>Inlines or schedules the continuation.</summary>
+        /// <param name="ignored">The antecedent task, which is ignored.</param>
+        /// <param name="canInlineContinuationTask">true if inlining is permitted; otherwise, false.</param>
+        internal sealed override void Run(Task ignored, bool canInlineContinuationTask)
+        {
+            // If we're targeting the default scheduler, we can use the faster path provided by the base class.
+            if (m_scheduler == TaskScheduler.Default)
+            {
+                base.Run(ignored, canInlineContinuationTask);
+            }
+            else
+            {
+                // We permit inlining if the caller allows us to, and 
+                // either we're on a thread pool thread (in which case we're fine running arbitrary code)
+                // or we're already on the target scheduler (in which case we'll just ask the scheduler
+                // whether it's ok to run here).  We include the IsThreadPoolThread check here, whereas
+                // we don't in AwaitTaskContinuation.Run, since here it expands what's allowed as opposed
+                // to in AwaitTaskContinuation.Run where it restricts what's allowed.
+                bool inlineIfPossible = canInlineContinuationTask &&
+                    (TaskScheduler.InternalCurrent == m_scheduler || ThreadPool.IsThreadPoolThread);
+
+                // Create the continuation task task. If we're allowed to inline, try to do so.  
+                // The target scheduler may still deny us from executing on this thread, in which case this'll be queued.
+                var task = CreateTask(state =>
+                {
+                    try { ((Action)state)(); }
+                    catch (Exception exc) { ThrowAsyncIfNecessary(exc); }
+                }, m_action, m_scheduler);
+
+                if (inlineIfPossible)
+                {
+                    InlineIfPossibleOrElseQueue(task, needsProtection: false);
+                }
+                else
+                {
+                    // We need to run asynchronously, so just schedule the task.
+                    try { task.ScheduleAndStart(needsProtection: false); }
+                    catch (TaskSchedulerException) { } // No further action is necessary, as ScheduleAndStart already transitioned task to faulted
+                }
+            }
+        }
+    }
+
+    /// <summary>Base task continuation class used for await continuations.</summary>
+    internal class AwaitTaskContinuation : TaskContinuation, IThreadPoolWorkItem
+    {
+        /// <summary>The ExecutionContext with which to run the continuation.</summary>
+        private readonly ExecutionContext m_capturedContext;
+        /// <summary>The action to invoke.</summary>
+        protected readonly Action m_action;
+
+        /// <summary>Initializes the continuation.</summary>
+        /// <param name="action">The action to invoke. Must not be null.</param>
+        /// <param name="flowExecutionContext">Whether to capture and restore ExecutionContext.</param>
+        internal AwaitTaskContinuation(Action action, bool flowExecutionContext)
+        {
+            Debug.Assert(action != null);
+            m_action = action;
+            if (flowExecutionContext)
+            {
+                m_capturedContext = ExecutionContext.Capture();
+            }
+        }
+
+        /// <summary>Creates a task to run the action with the specified state on the specified scheduler.</summary>
+        /// <param name="action">The action to run. Must not be null.</param>
+        /// <param name="state">The state to pass to the action. Must not be null.</param>
+        /// <param name="scheduler">The scheduler to target.</param>
+        /// <returns>The created task.</returns>
+        protected Task CreateTask(Action<object> action, object state, TaskScheduler scheduler)
+        {
+            Debug.Assert(action != null);
+            Debug.Assert(scheduler != null);
+
+            return new Task(
+                action, state, null, default,
+                TaskCreationOptions.None, InternalTaskOptions.QueuedByRuntime, scheduler)
+            {
+                CapturedContext = m_capturedContext
+            };
+        }
+
+        /// <summary>Inlines or schedules the continuation onto the default scheduler.</summary>
+        /// <param name="task">The antecedent task, which is ignored.</param>
+        /// <param name="canInlineContinuationTask">true if inlining is permitted; otherwise, false.</param>
+        internal override void Run(Task task, bool canInlineContinuationTask)
+        {
+            // For the base AwaitTaskContinuation, we allow inlining if our caller allows it
+            // and if we're in a "valid location" for it.  See the comments on 
+            // IsValidLocationForInlining for more about what's valid.  For performance
+            // reasons we would like to always inline, but we don't in some cases to avoid
+            // running arbitrary amounts of work in suspected "bad locations", like UI threads.
+            if (canInlineContinuationTask && IsValidLocationForInlining)
+            {
+                RunCallback(GetInvokeActionCallback(), m_action, ref Task.t_currentTask); // any exceptions from m_action will be handled by s_callbackRunAction
+            }
+            else
+            {
+                // We couldn't inline, so now we need to schedule it
+                ThreadPool.UnsafeQueueUserWorkItemInternal(this, preferLocal: true);
+            }
+        }
+
+        /// <summary>
+        /// Gets whether the current thread is an appropriate location to inline a continuation's execution.
+        /// </summary>
+        /// <remarks>
+        /// Returns whether SynchronizationContext is null and we're in the default scheduler.
+        /// If the await had a SynchronizationContext/TaskScheduler where it began and the 
+        /// default/ConfigureAwait(true) was used, then we won't be on this path.  If, however, 
+        /// ConfigureAwait(false) was used, or the SynchronizationContext and TaskScheduler were 
+        /// naturally null/Default, then we might end up here.  If we do, we need to make sure
+        /// that we don't execute continuations in a place that isn't set up to handle them, e.g.
+        /// running arbitrary amounts of code on the UI thread.  It would be "correct", but very
+        /// expensive, to always run the continuations asynchronously, incurring lots of context
+        /// switches and allocations and locks and the like.  As such, we employ the heuristic
+        /// that if the current thread has a non-null SynchronizationContext or a non-default
+        /// scheduler, then we better not run arbitrary continuations here.
+        /// </remarks>
+        internal static bool IsValidLocationForInlining
+        {
+            get
+            {
+                // If there's a SynchronizationContext, we'll be conservative and say 
+                // this is a bad location to inline.
+                var ctx = SynchronizationContext.Current;
+                if (ctx != null && ctx.GetType() != typeof(SynchronizationContext)) return false;
+
+                // Similarly, if there's a non-default TaskScheduler, we'll be conservative
+                // and say this is a bad location to inline.
+                var sched = TaskScheduler.InternalCurrent;
+                return sched == null || sched == TaskScheduler.Default;
+            }
+        }
+
+        void IThreadPoolWorkItem.Execute()
+        {
+            ExecutionContext context = m_capturedContext;
+
+            if (context == null)
+            {
+                m_action();
+                return;
+            }
+
+            // try
+            {
+                // We're not inside of a task, so t_currentTask doesn't need to be specially maintained.
+                // We're on a thread pool thread with no higher-level callers, so exceptions can just propagate.
+
+                ExecutionContext.CheckThreadPoolAndContextsAreDefault();
+                // If there's no execution context or Default, just invoke the delegate as ThreadPool is on Default context.
+                // We don't have to use ExecutionContext.Run for the Default context here as there is no extra processing after the delegate
+                if (context == null || context.IsDefault)
+                {
+                    m_action();
+                }
+                // If there is an execution context, get the cached delegate and run the action under the context.
+                else
+                {
+                    ExecutionContext.RunForThreadPoolUnsafe(context, s_invokeAction, m_action);
+                }
+
+                // ThreadPoolWorkQueue.Dispatch handles notifications and reset context back to default
+            }
+            // finally
+            // {
+            // }
+        }
+
+        /// <summary>Cached delegate that invokes an Action passed as an object parameter.</summary>
+        private readonly static ContextCallback s_invokeContextCallback = (state) => ((Action)state)();
+        private readonly static Action<Action> s_invokeAction = (action) => action();
+
+        [MethodImpl(MethodImplOptions.AggressiveInlining)]
+        protected static ContextCallback GetInvokeActionCallback() => s_invokeContextCallback;
+
+        /// <summary>Runs the callback synchronously with the provided state.</summary>
+        /// <param name="callback">The callback to run.</param>
+        /// <param name="state">The state to pass to the callback.</param>
+        /// <param name="currentTask">A reference to Task.t_currentTask.</param>
+        protected void RunCallback(ContextCallback callback, object state, ref Task currentTask)
+        {
+            Debug.Assert(callback != null);
+            Debug.Assert(currentTask == Task.t_currentTask);
+
+            // Pretend there's no current task, so that no task is seen as a parent
+            // and TaskScheduler.Current does not reflect false information
+            var prevCurrentTask = currentTask;
+            try
+            {
+                if (prevCurrentTask != null) currentTask = null;
+
+                ExecutionContext context = m_capturedContext;
+                if (context == null)
+                {
+                    // If there's no captured context, just run the callback directly.
+                    callback(state);
+                }
+                else
+                {
+                    // Otherwise, use the captured context to do so.
+                    ExecutionContext.RunInternal(context, callback, state);
+                }
+            }
+            catch (Exception exc) // we explicitly do not request handling of dangerous exceptions like AVs
+            {
+                ThrowAsyncIfNecessary(exc);
+            }
+            finally
+            {
+                // Restore the current task information
+                if (prevCurrentTask != null) currentTask = prevCurrentTask;
+            }
+        }
+
+        /// <summary>Invokes or schedules the action to be executed.</summary>
+        /// <param name="action">The action to invoke or queue.</param>
+        /// <param name="allowInlining">
+        /// true to allow inlining, or false to force the action to run asynchronously.
+        /// </param>
+        /// <remarks>
+        /// No ExecutionContext work is performed used.  This method is only used in the
+        /// case where a raw Action continuation delegate was stored into the Task, which
+        /// only happens in Task.SetContinuationForAwait if execution context flow was disabled
+        /// via using TaskAwaiter.UnsafeOnCompleted or a similar path.
+        /// </remarks>
+        internal static void RunOrScheduleAction(Action action, bool allowInlining)
+        {
+            ref Task currentTask = ref Task.t_currentTask;
+            Task prevCurrentTask = currentTask;
+
+            // If we're not allowed to run here, schedule the action
+            if (!allowInlining || !IsValidLocationForInlining)
+            {
+                UnsafeScheduleAction(action, prevCurrentTask);
+                return;
+            }
+
+            // Otherwise, run it, making sure that t_currentTask is null'd out appropriately during the execution
+            try
+            {
+                if (prevCurrentTask != null) currentTask = null;
+                action();
+            }
+            catch (Exception exception)
+            {
+                ThrowAsyncIfNecessary(exception);
+            }
+            finally
+            {
+                if (prevCurrentTask != null) currentTask = prevCurrentTask;
+            }
+        }
+
+        /// <summary>Invokes or schedules the action to be executed.</summary>
+        /// <param name="box">The <see cref="IAsyncStateMachineBox"/> that needs to be invoked or queued.</param>
+        /// <param name="allowInlining">
+        /// true to allow inlining, or false to force the box's action to run asynchronously.
+        /// </param>
+        internal static void RunOrScheduleAction(IAsyncStateMachineBox box, bool allowInlining)
+        {
+            // Same logic as in the RunOrScheduleAction(Action, ...) overload, except invoking
+            // box.Invoke instead of action().
+
+            ref Task currentTask = ref Task.t_currentTask;
+            Task prevCurrentTask = currentTask;
+
+            // If we're not allowed to run here, schedule the action
+            if (!allowInlining || !IsValidLocationForInlining)
+            {
+                ThreadPool.UnsafeQueueUserWorkItemInternal(box, preferLocal: true);
+                return;
+            }
+
+            // Otherwise, run it, making sure that t_currentTask is null'd out appropriately during the execution
+            try
+            {
+                if (prevCurrentTask != null) currentTask = null;
+                box.MoveNext();
+            }
+            catch (Exception exception)
+            {
+                ThrowAsyncIfNecessary(exception);
+            }
+            finally
+            {
+                if (prevCurrentTask != null) currentTask = prevCurrentTask;
+            }
+        }
+
+        /// <summary>Schedules the action to be executed.  No ExecutionContext work is performed used.</summary>
+        /// <param name="action">The action to invoke or queue.</param>
+        internal static void UnsafeScheduleAction(Action action, Task task)
+        {
+            ThreadPool.UnsafeQueueUserWorkItemInternal(
+                new AwaitTaskContinuation(action, flowExecutionContext: false),
+                preferLocal: true);
+        }
+
+        /// <summary>Throws the exception asynchronously on the ThreadPool.</summary>
+        /// <param name="exc">The exception to throw.</param>
+        protected static void ThrowAsyncIfNecessary(Exception exc)
+        {
+            // Awaits should never experience an exception (other than an TAE or ADUE), 
+            // unless a malicious user is explicitly passing a throwing action into the TaskAwaiter. 
+            // We don't want to allow the exception to propagate on this stack, as it'll emerge in random places, 
+            // and we can't fail fast, as that would allow for elevation of privilege. Instead, since this 
+            // would have executed on the thread pool otherwise, let it propagate there.
+
+            //if (!(exc is ThreadAbortException || exc is AppDomainUnloadedException))
+            {
+//                RuntimeAugments.ReportUnhandledException(exc);
+            }
+        }
+
+        internal override Delegate[] GetDelegateContinuationsForDebugger()
+        {
+            Debug.Assert(m_action != null);
+            return new Delegate[] { AsyncMethodBuilderCore.TryGetStateMachineForDebugger(m_action) };
+        }
+    }
+}

+ 3043 - 0
mcs/class/System.Private.CoreLib/temp/TaskFactory.cs

@@ -0,0 +1,3043 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
+//
+//
+//
+// There are a plethora of common patterns for which Tasks are created.  TaskFactory encodes 
+// these patterns into helper methods.  These helpers also pick up default configuration settings 
+// applicable to the entire factory and configurable through its constructors.
+//
+// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
+
+using System;
+using System.Collections.Generic;
+using System.Security;
+using System.Runtime.CompilerServices;
+using System.Threading;
+using System.Diagnostics;
+
+using AsyncStatus = Internal.Runtime.Augments.AsyncStatus;
+using CausalityRelation = Internal.Runtime.Augments.CausalityRelation;
+using CausalitySource = Internal.Runtime.Augments.CausalitySource;
+using CausalityTraceLevel = Internal.Runtime.Augments.CausalityTraceLevel;
+using CausalitySynchronousWork = Internal.Runtime.Augments.CausalitySynchronousWork;
+
+namespace System.Threading.Tasks
+{
+    /// <summary>
+    /// Provides support for creating and scheduling
+    /// <see cref="T:System.Threading.Tasks.Task">Tasks</see>.
+    /// </summary>
+    /// <remarks>
+    /// <para>
+    /// There are many common patterns for which tasks are relevant. The <see cref="TaskFactory"/>
+    /// class encodes some of these patterns into methods that pick up default settings, which are
+    /// configurable through its constructors.
+    /// </para>
+    /// <para>
+    /// A default instance of <see cref="TaskFactory"/> is available through the
+    /// <see cref="System.Threading.Tasks.Task.Factory">Task.Factory</see> property.
+    /// </para>
+    /// </remarks>
+    public class TaskFactory
+    {
+        // member variables
+        private readonly CancellationToken m_defaultCancellationToken;
+        private readonly TaskScheduler m_defaultScheduler;
+        private readonly TaskCreationOptions m_defaultCreationOptions;
+        private readonly TaskContinuationOptions m_defaultContinuationOptions;
+
+        private TaskScheduler DefaultScheduler => m_defaultScheduler ?? TaskScheduler.Current;
+
+        // sister method to above property -- avoids a TLS lookup
+        private TaskScheduler GetDefaultScheduler(Task currTask)
+        {
+            return
+                m_defaultScheduler ??
+                (currTask != null && (currTask.CreationOptions & TaskCreationOptions.HideScheduler) == 0 ? currTask.ExecutingTaskScheduler :
+                 TaskScheduler.Default);
+        }
+
+        /* Constructors */
+
+        // ctor parameters provide defaults for the factory, which can be overridden by options provided to
+        // specific calls on the factory
+
+
+        /// <summary>
+        /// Initializes a <see cref="TaskFactory"/> instance with the default configuration.
+        /// </summary>
+        /// <remarks>
+        /// This constructor creates a <see cref="TaskFactory"/> instance with a default configuration. The
+        /// <see cref="TaskCreationOptions"/> property is initialized to
+        /// <see cref="System.Threading.Tasks.TaskCreationOptions.None">TaskCreationOptions.None</see>, the
+        /// <see cref="TaskContinuationOptions"/> property is initialized to <see
+        /// cref="System.Threading.Tasks.TaskContinuationOptions.None">TaskContinuationOptions.None</see>,
+        /// and the <see cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see> property is
+        /// initialized to the current scheduler (see <see
+        /// cref="System.Threading.Tasks.TaskScheduler.Current">TaskScheduler.Current</see>).
+        /// </remarks>
+        public TaskFactory()
+            : this(default, TaskCreationOptions.None, TaskContinuationOptions.None, null)
+        {
+        }
+
+        /// <summary>
+        /// Initializes a <see cref="TaskFactory"/> instance with the specified configuration.
+        /// </summary>
+        /// <param name="cancellationToken">The default <see cref="CancellationToken"/> that will be assigned 
+        /// to tasks created by this <see cref="TaskFactory"/> unless another CancellationToken is explicitly specified 
+        /// while calling the factory methods.</param>
+        /// <remarks>
+        /// This constructor creates a <see cref="TaskFactory"/> instance with a default configuration. The
+        /// <see cref="TaskCreationOptions"/> property is initialized to
+        /// <see cref="System.Threading.Tasks.TaskCreationOptions.None">TaskCreationOptions.None</see>, the
+        /// <see cref="TaskContinuationOptions"/> property is initialized to <see
+        /// cref="System.Threading.Tasks.TaskContinuationOptions.None">TaskContinuationOptions.None</see>,
+        /// and the <see cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see> property is
+        /// initialized to the current scheduler (see <see
+        /// cref="System.Threading.Tasks.TaskScheduler.Current">TaskScheduler.Current</see>).
+        /// </remarks>
+        public TaskFactory(CancellationToken cancellationToken)
+            : this(cancellationToken, TaskCreationOptions.None, TaskContinuationOptions.None, null)
+        {
+        }
+
+        /// <summary>
+        /// Initializes a <see cref="TaskFactory"/> instance with the specified configuration.
+        /// </summary>
+        /// <param name="scheduler">
+        /// The <see cref="System.Threading.Tasks.TaskScheduler">
+        /// TaskScheduler</see> to use to schedule any tasks created with this TaskFactory. A null value
+        /// indicates that the current TaskScheduler should be used.
+        /// </param>
+        /// <remarks>
+        /// With this constructor, the
+        /// <see cref="TaskCreationOptions"/> property is initialized to
+        /// <see cref="System.Threading.Tasks.TaskCreationOptions.None">TaskCreationOptions.None</see>, the
+        /// <see cref="TaskContinuationOptions"/> property is initialized to <see
+        /// cref="System.Threading.Tasks.TaskContinuationOptions.None">TaskContinuationOptions.None</see>,
+        /// and the <see cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see> property is
+        /// initialized to <paramref name="scheduler"/>, unless it's null, in which case the property is
+        /// initialized to the current scheduler (see <see
+        /// cref="System.Threading.Tasks.TaskScheduler.Current">TaskScheduler.Current</see>).
+        /// </remarks>
+        public TaskFactory(TaskScheduler scheduler) // null means to use TaskScheduler.Current
+            : this(default, TaskCreationOptions.None, TaskContinuationOptions.None, scheduler)
+        {
+        }
+
+        /// <summary>
+        /// Initializes a <see cref="TaskFactory"/> instance with the specified configuration.
+        /// </summary>
+        /// <param name="creationOptions">
+        /// The default <see cref="System.Threading.Tasks.TaskCreationOptions">
+        /// TaskCreationOptions</see> to use when creating tasks with this TaskFactory.
+        /// </param>
+        /// <param name="continuationOptions">
+        /// The default <see cref="System.Threading.Tasks.TaskContinuationOptions">
+        /// TaskContinuationOptions</see> to use when creating continuation tasks with this TaskFactory.
+        /// </param>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">
+        /// The exception that is thrown when the
+        /// <paramref name="creationOptions"/> argument or the <paramref name="continuationOptions"/>
+        /// argument specifies an invalid value.
+        /// </exception>
+        /// <remarks>
+        /// With this constructor, the
+        /// <see cref="TaskCreationOptions"/> property is initialized to <paramref name="creationOptions"/>,
+        /// the
+        /// <see cref="TaskContinuationOptions"/> property is initialized to <paramref
+        /// name="continuationOptions"/>, and the <see
+        /// cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see> property is initialized to the
+        /// current scheduler (see <see
+        /// cref="System.Threading.Tasks.TaskScheduler.Current">TaskScheduler.Current</see>).
+        /// </remarks>
+        public TaskFactory(TaskCreationOptions creationOptions, TaskContinuationOptions continuationOptions)
+            : this(default, creationOptions, continuationOptions, null)
+        {
+        }
+
+        /// <summary>
+        /// Initializes a <see cref="TaskFactory"/> instance with the specified configuration.
+        /// </summary>
+        /// <param name="cancellationToken">The default <see cref="CancellationToken"/> that will be assigned 
+        /// to tasks created by this <see cref="TaskFactory"/> unless another CancellationToken is explicitly specified 
+        /// while calling the factory methods.</param>
+        /// <param name="creationOptions">
+        /// The default <see cref="System.Threading.Tasks.TaskCreationOptions">
+        /// TaskCreationOptions</see> to use when creating tasks with this TaskFactory.
+        /// </param>
+        /// <param name="continuationOptions">
+        /// The default <see cref="System.Threading.Tasks.TaskContinuationOptions">
+        /// TaskContinuationOptions</see> to use when creating continuation tasks with this TaskFactory.
+        /// </param>
+        /// <param name="scheduler">
+        /// The default <see cref="System.Threading.Tasks.TaskScheduler">
+        /// TaskScheduler</see> to use to schedule any Tasks created with this TaskFactory. A null value
+        /// indicates that TaskScheduler.Current should be used.
+        /// </param>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">
+        /// The exception that is thrown when the
+        /// <paramref name="creationOptions"/> argument or the <paramref name="continuationOptions"/>
+        /// argumentspecifies an invalid value.
+        /// </exception>
+        /// <remarks>
+        /// With this constructor, the
+        /// <see cref="TaskCreationOptions"/> property is initialized to <paramref name="creationOptions"/>,
+        /// the
+        /// <see cref="TaskContinuationOptions"/> property is initialized to <paramref
+        /// name="continuationOptions"/>, and the <see
+        /// cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see> property is initialized to
+        /// <paramref name="scheduler"/>, unless it's null, in which case the property is initialized to the
+        /// current scheduler (see <see
+        /// cref="System.Threading.Tasks.TaskScheduler.Current">TaskScheduler.Current</see>).
+        /// </remarks>
+        public TaskFactory(CancellationToken cancellationToken, TaskCreationOptions creationOptions, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
+        {
+            CheckMultiTaskContinuationOptions(continuationOptions);
+            CheckCreationOptions(creationOptions);
+
+            m_defaultCancellationToken = cancellationToken;
+            m_defaultScheduler = scheduler;
+            m_defaultCreationOptions = creationOptions;
+            m_defaultContinuationOptions = continuationOptions;
+        }
+
+        internal static void CheckCreationOptions(TaskCreationOptions creationOptions)
+        {
+            // Check for validity of options
+            if ((creationOptions &
+                    ~(TaskCreationOptions.AttachedToParent |
+                      TaskCreationOptions.DenyChildAttach |
+                      TaskCreationOptions.HideScheduler |
+                      TaskCreationOptions.LongRunning |
+                      TaskCreationOptions.PreferFairness |
+                      TaskCreationOptions.RunContinuationsAsynchronously)) != 0)
+            {
+                ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.creationOptions);
+            }
+        }
+
+        /* Properties */
+
+        /// <summary>
+        /// Gets the default <see cref="System.Threading.CancellationToken">CancellationToken</see> of this
+        /// TaskFactory.
+        /// </summary>
+        /// <remarks>
+        /// This property returns the default <see cref="CancellationToken"/> that will be assigned to all 
+        /// tasks created by this factory unless another CancellationToken value is explicitly specified 
+        /// during the call to the factory methods.
+        /// </remarks>
+        public CancellationToken CancellationToken { get { return m_defaultCancellationToken; } }
+
+        /// <summary>
+        /// Gets the <see cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see> of this
+        /// TaskFactory.
+        /// </summary>
+        /// <remarks>
+        /// This property returns the default scheduler for this factory.  It will be used to schedule all 
+        /// tasks unless another scheduler is explicitly specified during calls to this factory's methods.  
+        /// If null, <see cref="System.Threading.Tasks.TaskScheduler.Current">TaskScheduler.Current</see> 
+        /// will be used.
+        /// </remarks>
+        public TaskScheduler Scheduler { get { return m_defaultScheduler; } }
+
+        /// <summary>
+        /// Gets the <see cref="System.Threading.Tasks.TaskCreationOptions">TaskCreationOptions
+        /// </see> value of this TaskFactory.
+        /// </summary>
+        /// <remarks>
+        /// This property returns the default creation options for this factory.  They will be used to create all 
+        /// tasks unless other options are explicitly specified during calls to this factory's methods.
+        /// </remarks>
+        public TaskCreationOptions CreationOptions { get { return m_defaultCreationOptions; } }
+
+        /// <summary>
+        /// Gets the <see cref="System.Threading.Tasks.TaskCreationOptions">TaskContinuationOptions
+        /// </see> value of this TaskFactory.
+        /// </summary>
+        /// <remarks>
+        /// This property returns the default continuation options for this factory.  They will be used to create 
+        /// all continuation tasks unless other options are explicitly specified during calls to this factory's methods.
+        /// </remarks>
+        public TaskContinuationOptions ContinuationOptions { get { return m_defaultContinuationOptions; } }
+
+        //
+        // StartNew methods
+        //
+
+        /// <summary>
+        /// Creates and starts a <see cref="T:System.Threading.Tasks.Task">Task</see>.
+        /// </summary>
+        /// <param name="action">The action delegate to execute asynchronously.</param>
+        /// <returns>The started <see cref="T:System.Threading.Tasks.Task">Task</see>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref name="action"/> 
+        /// argument is null.</exception>
+        /// <remarks>
+        /// Calling StartNew is functionally equivalent to creating a Task using one of its constructors 
+        /// and then calling 
+        /// <see cref="System.Threading.Tasks.Task.Start()">Start</see> to schedule it for execution.  However,
+        /// unless creation and scheduling must be separated, StartNew is the recommended
+        /// approach for both simplicity and performance.
+        /// </remarks>
+        public Task StartNew(Action action)
+        {
+            Task currTask = Task.InternalCurrent;
+            return Task.InternalStartNew(currTask, action, null, m_defaultCancellationToken, GetDefaultScheduler(currTask),
+                m_defaultCreationOptions, InternalTaskOptions.None);
+        }
+
+        /// <summary>
+        /// Creates and starts a <see cref="T:System.Threading.Tasks.Task">Task</see>.
+        /// </summary>
+        /// <param name="action">The action delegate to execute asynchronously.</param>
+        /// <param name="cancellationToken">The <see cref="CancellationToken"/> that will be assigned to the new task.</param>
+        /// <returns>The started <see cref="T:System.Threading.Tasks.Task">Task</see>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref name="action"/> 
+        /// argument is null.</exception>
+        /// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
+        /// has already been disposed.
+        /// </exception>
+        /// <remarks>
+        /// Calling StartNew is functionally equivalent to creating a Task using one of its constructors 
+        /// and then calling 
+        /// <see cref="System.Threading.Tasks.Task.Start()">Start</see> to schedule it for execution.  However,
+        /// unless creation and scheduling must be separated, StartNew is the recommended
+        /// approach for both simplicity and performance.
+        /// </remarks>
+        public Task StartNew(Action action, CancellationToken cancellationToken)
+        {
+            Task currTask = Task.InternalCurrent;
+            return Task.InternalStartNew(currTask, action, null, cancellationToken, GetDefaultScheduler(currTask),
+                m_defaultCreationOptions, InternalTaskOptions.None);
+        }
+
+        /// <summary>
+        /// Creates and starts a <see cref="T:System.Threading.Tasks.Task">Task</see>.
+        /// </summary>
+        /// <param name="action">The action delegate to execute asynchronously.</param>
+        /// <param name="creationOptions">A TaskCreationOptions value that controls the behavior of the
+        /// created
+        /// <see cref="T:System.Threading.Tasks.Task">Task.</see></param>
+        /// <returns>The started <see cref="T:System.Threading.Tasks.Task">Task</see>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref
+        /// name="action"/>
+        /// argument is null.</exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">The exception that is thrown when the
+        /// <paramref name="creationOptions"/> argument specifies an invalid TaskCreationOptions
+        /// value.</exception>
+        /// <remarks>
+        /// Calling StartNew is functionally equivalent to creating a Task using one of its constructors and
+        /// then calling
+        /// <see cref="System.Threading.Tasks.Task.Start()">Start</see> to schedule it for execution.
+        /// However, unless creation and scheduling must be separated, StartNew is the recommended approach
+        /// for both simplicity and performance.
+        /// </remarks>
+        public Task StartNew(Action action, TaskCreationOptions creationOptions)
+        {
+            Task currTask = Task.InternalCurrent;
+            return Task.InternalStartNew(currTask, action, null, m_defaultCancellationToken, GetDefaultScheduler(currTask), creationOptions,
+                InternalTaskOptions.None);
+        }
+
+        /// <summary>
+        /// Creates and starts a <see cref="T:System.Threading.Tasks.Task">Task</see>.
+        /// </summary>
+        /// <param name="action">The action delegate to execute asynchronously.</param>
+        /// <param name="cancellationToken">The <see cref="CancellationToken"/> that will be assigned to the new <see cref="Task"/></param>
+        /// <param name="creationOptions">A TaskCreationOptions value that controls the behavior of the
+        /// created
+        /// <see cref="T:System.Threading.Tasks.Task">Task.</see></param>
+        /// <param name="scheduler">The <see
+        /// cref="T:System.Threading.Tasks.TaskScheduler">TaskScheduler</see>
+        /// that is used to schedule the created <see
+        /// cref="T:System.Threading.Tasks.Task">Task</see>.</param>
+        /// <returns>The started <see cref="T:System.Threading.Tasks.Task">Task</see>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref
+        /// name="action"/>
+        /// argument is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref
+        /// name="scheduler"/>
+        /// argument is null.</exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">The exception that is thrown when the
+        /// <paramref name="creationOptions"/> argument specifies an invalid TaskCreationOptions
+        /// value.</exception>
+        /// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
+        /// has already been disposed.
+        /// </exception>
+        /// <remarks>
+        /// Calling StartNew is functionally equivalent to creating a Task using one of its constructors and
+        /// then calling
+        /// <see cref="System.Threading.Tasks.Task.Start()">Start</see> to schedule it for execution.
+        /// However, unless creation and scheduling must be separated, StartNew is the recommended approach
+        /// for both simplicity and performance.
+        /// </remarks>
+        public Task StartNew(Action action, CancellationToken cancellationToken, TaskCreationOptions creationOptions, TaskScheduler scheduler)
+        {
+            return Task.InternalStartNew(
+                Task.InternalCurrentIfAttached(creationOptions), action, null, cancellationToken, scheduler, creationOptions,
+                InternalTaskOptions.None);
+        }
+
+
+        /// <summary>
+        /// Creates and starts a <see cref="T:System.Threading.Tasks.Task">Task</see>.
+        /// </summary>
+        /// <param name="action">The action delegate to execute asynchronously.</param>
+        /// <param name="state">An object containing data to be used by the <paramref name="action"/>
+        /// delegate.</param>
+        /// <returns>The started <see cref="T:System.Threading.Tasks.Task">Task</see>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref
+        /// name="action"/>
+        /// argument is null.</exception>
+        /// <remarks>
+        /// Calling StartNew is functionally equivalent to creating a Task using one of its constructors and
+        /// then calling
+        /// <see cref="System.Threading.Tasks.Task.Start()">Start</see> to schedule it for execution.
+        /// However, unless creation and scheduling must be separated, StartNew is the recommended approach
+        /// for both simplicity and performance.
+        /// </remarks>
+        public Task StartNew(Action<object> action, object state)
+        {
+            Task currTask = Task.InternalCurrent;
+            return Task.InternalStartNew(currTask, action, state, m_defaultCancellationToken, GetDefaultScheduler(currTask),
+                m_defaultCreationOptions, InternalTaskOptions.None);
+        }
+
+
+        /// <summary>
+        /// Creates and starts a <see cref="T:System.Threading.Tasks.Task">Task</see>.
+        /// </summary>
+        /// <param name="action">The action delegate to execute asynchronously.</param>
+        /// <param name="state">An object containing data to be used by the <paramref name="action"/>
+        /// delegate.</param>
+        /// <param name="cancellationToken">The <see cref="CancellationToken"/> that will be assigned to the new <see cref="Task"/></param>
+        /// <returns>The started <see cref="T:System.Threading.Tasks.Task">Task</see>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref
+        /// name="action"/>
+        /// argument is null.</exception>
+        /// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
+        /// has already been disposed.
+        /// </exception>
+        /// <remarks>
+        /// Calling StartNew is functionally equivalent to creating a Task using one of its constructors and
+        /// then calling
+        /// <see cref="System.Threading.Tasks.Task.Start()">Start</see> to schedule it for execution.
+        /// However, unless creation and scheduling must be separated, StartNew is the recommended approach
+        /// for both simplicity and performance.
+        /// </remarks>
+        public Task StartNew(Action<object> action, object state, CancellationToken cancellationToken)
+        {
+            Task currTask = Task.InternalCurrent;
+            return Task.InternalStartNew(currTask, action, state, cancellationToken, GetDefaultScheduler(currTask),
+                m_defaultCreationOptions, InternalTaskOptions.None);
+        }
+
+        /// <summary>
+        /// Creates and starts a <see cref="T:System.Threading.Tasks.Task">Task</see>.
+        /// </summary>
+        /// <param name="action">The action delegate to execute asynchronously.</param>
+        /// <param name="state">An object containing data to be used by the <paramref name="action"/>
+        /// delegate.</param>
+        /// <param name="creationOptions">A TaskCreationOptions value that controls the behavior of the
+        /// created
+        /// <see cref="T:System.Threading.Tasks.Task">Task.</see></param>
+        /// <returns>The started <see cref="T:System.Threading.Tasks.Task">Task</see>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref
+        /// name="action"/>
+        /// argument is null.</exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">The exception that is thrown when the
+        /// <paramref name="creationOptions"/> argument specifies an invalid TaskCreationOptions
+        /// value.</exception>
+        /// <remarks>
+        /// Calling StartNew is functionally equivalent to creating a Task using one of its constructors and
+        /// then calling
+        /// <see cref="System.Threading.Tasks.Task.Start()">Start</see> to schedule it for execution.
+        /// However, unless creation and scheduling must be separated, StartNew is the recommended approach
+        /// for both simplicity and performance.
+        /// </remarks>
+        public Task StartNew(Action<object> action, object state, TaskCreationOptions creationOptions)
+        {
+            Task currTask = Task.InternalCurrent;
+            return Task.InternalStartNew(currTask, action, state, m_defaultCancellationToken, GetDefaultScheduler(currTask),
+                creationOptions, InternalTaskOptions.None);
+        }
+
+        /// <summary>
+        /// Creates and starts a <see cref="T:System.Threading.Tasks.Task">Task</see>.
+        /// </summary>
+        /// <param name="action">The action delegate to execute asynchronously.</param>
+        /// <param name="state">An object containing data to be used by the <paramref name="action"/>
+        /// delegate.</param>
+        /// <param name="cancellationToken">The <see cref="CancellationToken"/> that will be assigned to the new task.</param>
+        /// <param name="creationOptions">A TaskCreationOptions value that controls the behavior of the
+        /// created
+        /// <see cref="T:System.Threading.Tasks.Task">Task.</see></param>
+        /// <param name="scheduler">The <see
+        /// cref="T:System.Threading.Tasks.TaskScheduler">TaskScheduler</see>
+        /// that is used to schedule the created <see
+        /// cref="T:System.Threading.Tasks.Task">Task</see>.</param>
+        /// <returns>The started <see cref="T:System.Threading.Tasks.Task">Task</see>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref
+        /// name="action"/>
+        /// argument is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref
+        /// name="scheduler"/>
+        /// argument is null.</exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">The exception that is thrown when the
+        /// <paramref name="creationOptions"/> argument specifies an invalid TaskCreationOptions
+        /// value.</exception>
+        /// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
+        /// has already been disposed.
+        /// </exception>
+        /// <remarks>
+        /// Calling StartNew is functionally equivalent to creating a Task using one of its constructors and
+        /// then calling
+        /// <see cref="System.Threading.Tasks.Task.Start()">Start</see> to schedule it for execution.
+        /// However, unless creation and scheduling must be separated, StartNew is the recommended approach
+        /// for both simplicity and performance.
+        /// </remarks>
+        public Task StartNew(Action<object> action, object state, CancellationToken cancellationToken,
+                            TaskCreationOptions creationOptions, TaskScheduler scheduler)
+        {
+            return Task.InternalStartNew(
+                Task.InternalCurrentIfAttached(creationOptions), action, state, cancellationToken, scheduler,
+                creationOptions, InternalTaskOptions.None);
+        }
+
+        /// <summary>
+        /// Creates and starts a <see cref="T:System.Threading.Tasks.Task{TResult}"/>.
+        /// </summary>
+        /// <typeparam name="TResult">The type of the result available through the
+        /// <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>.
+        /// </typeparam>
+        /// <param name="function">A function delegate that returns the future result to be available through
+        /// the <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</param>
+        /// <returns>The started <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref
+        /// name="function"/>
+        /// argument is null.</exception>
+        /// <remarks>
+        /// Calling StartNew is functionally equivalent to creating a <see cref="Task{TResult}"/> using one
+        /// of its constructors and then calling
+        /// <see cref="System.Threading.Tasks.Task.Start()">Start</see> to schedule it for execution.
+        /// However, unless creation and scheduling must be separated, StartNew is the recommended approach
+        /// for both simplicity and performance.
+        /// </remarks>
+        public Task<TResult> StartNew<TResult>(Func<TResult> function)
+        {
+            Task currTask = Task.InternalCurrent;
+            return Task<TResult>.StartNew(currTask, function, m_defaultCancellationToken,
+                m_defaultCreationOptions, InternalTaskOptions.None, GetDefaultScheduler(currTask));
+        }
+
+
+        /// <summary>
+        /// Creates and starts a <see cref="T:System.Threading.Tasks.Task{TResult}"/>.
+        /// </summary>
+        /// <typeparam name="TResult">The type of the result available through the
+        /// <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>.
+        /// </typeparam>
+        /// <param name="function">A function delegate that returns the future result to be available through
+        /// the <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</param>
+        /// <param name="cancellationToken">The <see cref="CancellationToken"/> that will be assigned to the new <see cref="Task"/></param>
+        /// <returns>The started <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref
+        /// name="function"/>
+        /// argument is null.</exception>
+        /// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
+        /// has already been disposed.
+        /// </exception>
+        /// <remarks>
+        /// Calling StartNew is functionally equivalent to creating a <see cref="Task{TResult}"/> using one
+        /// of its constructors and then calling
+        /// <see cref="System.Threading.Tasks.Task.Start()">Start</see> to schedule it for execution.
+        /// However, unless creation and scheduling must be separated, StartNew is the recommended approach
+        /// for both simplicity and performance.
+        /// </remarks>
+        public Task<TResult> StartNew<TResult>(Func<TResult> function, CancellationToken cancellationToken)
+        {
+            Task currTask = Task.InternalCurrent;
+            return Task<TResult>.StartNew(currTask, function, cancellationToken,
+                m_defaultCreationOptions, InternalTaskOptions.None, GetDefaultScheduler(currTask));
+        }
+
+        /// <summary>
+        /// Creates and starts a <see cref="T:System.Threading.Tasks.Task{TResult}"/>.
+        /// </summary>
+        /// <typeparam name="TResult">The type of the result available through the
+        /// <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>.
+        /// </typeparam>
+        /// <param name="function">A function delegate that returns the future result to be available through
+        /// the <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</param>
+        /// <param name="creationOptions">A TaskCreationOptions value that controls the behavior of the
+        /// created
+        /// <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</param>
+        /// <returns>The started <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref
+        /// name="function"/>
+        /// argument is null.</exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">The exception that is thrown when the
+        /// <paramref name="creationOptions"/> argument specifies an invalid TaskCreationOptions
+        /// value.</exception>
+        /// <remarks>
+        /// Calling StartNew is functionally equivalent to creating a <see cref="Task{TResult}"/> using one
+        /// of its constructors and then calling
+        /// <see cref="System.Threading.Tasks.Task.Start()">Start</see> to schedule it for execution.
+        /// However, unless creation and scheduling must be separated, StartNew is the recommended approach
+        /// for both simplicity and performance.
+        /// </remarks>
+        public Task<TResult> StartNew<TResult>(Func<TResult> function, TaskCreationOptions creationOptions)
+        {
+            Task currTask = Task.InternalCurrent;
+            return Task<TResult>.StartNew(currTask, function, m_defaultCancellationToken,
+                creationOptions, InternalTaskOptions.None, GetDefaultScheduler(currTask));
+        }
+
+        /// <summary>
+        /// Creates and starts a <see cref="T:System.Threading.Tasks.Task{TResult}"/>.
+        /// </summary>
+        /// <typeparam name="TResult">The type of the result available through the
+        /// <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>.
+        /// </typeparam>
+        /// <param name="function">A function delegate that returns the future result to be available through
+        /// the <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</param>
+        /// <param name="cancellationToken">The <see cref="CancellationToken"/> that will be assigned to the new task.</param>
+        /// <param name="creationOptions">A TaskCreationOptions value that controls the behavior of the
+        /// created
+        /// <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</param>
+        /// <param name="scheduler">The <see
+        /// cref="T:System.Threading.Tasks.TaskScheduler">TaskScheduler</see>
+        /// that is used to schedule the created <see cref="T:System.Threading.Tasks.Task{TResult}">
+        /// Task{TResult}</see>.</param>
+        /// <returns>The started <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref
+        /// name="function"/>
+        /// argument is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref
+        /// name="scheduler"/>
+        /// argument is null.</exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">The exception that is thrown when the
+        /// <paramref name="creationOptions"/> argument specifies an invalid TaskCreationOptions
+        /// value.</exception>
+        /// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
+        /// has already been disposed.
+        /// </exception>
+        /// <remarks>
+        /// Calling StartNew is functionally equivalent to creating a <see cref="Task{TResult}"/> using one
+        /// of its constructors and then calling
+        /// <see cref="System.Threading.Tasks.Task.Start()">Start</see> to schedule it for execution.
+        /// However, unless creation and scheduling must be separated, StartNew is the recommended approach
+        /// for both simplicity and performance.
+        /// </remarks>
+        public Task<TResult> StartNew<TResult>(Func<TResult> function, CancellationToken cancellationToken, TaskCreationOptions creationOptions, TaskScheduler scheduler)
+        {
+            return Task<TResult>.StartNew(
+                Task.InternalCurrentIfAttached(creationOptions), function, cancellationToken,
+                creationOptions, InternalTaskOptions.None, scheduler);
+        }
+
+        /// <summary>
+        /// Creates and starts a <see cref="T:System.Threading.Tasks.Task{TResult}"/>.
+        /// </summary>
+        /// <typeparam name="TResult">The type of the result available through the
+        /// <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>.
+        /// </typeparam>
+        /// <param name="function">A function delegate that returns the future result to be available through
+        /// the <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</param>
+        /// <param name="state">An object containing data to be used by the <paramref name="function"/>
+        /// delegate.</param>
+        /// <returns>The started <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref
+        /// name="function"/>
+        /// argument is null.</exception>
+        /// <remarks>
+        /// Calling StartNew is functionally equivalent to creating a <see cref="Task{TResult}"/> using one
+        /// of its constructors and then calling
+        /// <see cref="System.Threading.Tasks.Task.Start()">Start</see> to schedule it for execution.
+        /// However, unless creation and scheduling must be separated, StartNew is the recommended approach
+        /// for both simplicity and performance.
+        /// </remarks>
+        public Task<TResult> StartNew<TResult>(Func<object, TResult> function, object state)
+        {
+            Task currTask = Task.InternalCurrent;
+            return Task<TResult>.StartNew(currTask, function, state, m_defaultCancellationToken,
+                m_defaultCreationOptions, InternalTaskOptions.None, GetDefaultScheduler(currTask));
+        }
+
+
+        /// <summary>
+        /// Creates and starts a <see cref="T:System.Threading.Tasks.Task{TResult}"/>.
+        /// </summary>
+        /// <typeparam name="TResult">The type of the result available through the
+        /// <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>.
+        /// </typeparam>
+        /// <param name="function">A function delegate that returns the future result to be available through
+        /// the <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</param>
+        /// <param name="state">An object containing data to be used by the <paramref name="function"/>
+        /// delegate.</param>
+        /// <param name="cancellationToken">The <see cref="CancellationToken"/> that will be assigned to the new <see cref="Task"/></param>
+        /// <returns>The started <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref
+        /// name="function"/>
+        /// argument is null.</exception>
+        /// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
+        /// has already been disposed.
+        /// </exception>
+        /// <remarks>
+        /// Calling StartNew is functionally equivalent to creating a <see cref="Task{TResult}"/> using one
+        /// of its constructors and then calling
+        /// <see cref="System.Threading.Tasks.Task.Start()">Start</see> to schedule it for execution.
+        /// However, unless creation and scheduling must be separated, StartNew is the recommended approach
+        /// for both simplicity and performance.
+        /// </remarks>
+        public Task<TResult> StartNew<TResult>(Func<object, TResult> function, object state, CancellationToken cancellationToken)
+        {
+            Task currTask = Task.InternalCurrent;
+            return Task<TResult>.StartNew(currTask, function, state, cancellationToken,
+                m_defaultCreationOptions, InternalTaskOptions.None, GetDefaultScheduler(currTask));
+        }
+
+        /// <summary>
+        /// Creates and starts a <see cref="T:System.Threading.Tasks.Task{TResult}"/>.
+        /// </summary>
+        /// <typeparam name="TResult">The type of the result available through the
+        /// <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>.
+        /// </typeparam>
+        /// <param name="function">A function delegate that returns the future result to be available through
+        /// the <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</param>
+        /// <param name="state">An object containing data to be used by the <paramref name="function"/>
+        /// delegate.</param>
+        /// <param name="creationOptions">A TaskCreationOptions value that controls the behavior of the
+        /// created
+        /// <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</param>
+        /// <returns>The started <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref
+        /// name="function"/>
+        /// argument is null.</exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">The exception that is thrown when the
+        /// <paramref name="creationOptions"/> argument specifies an invalid TaskCreationOptions
+        /// value.</exception>
+        /// <remarks>
+        /// Calling StartNew is functionally equivalent to creating a <see cref="Task{TResult}"/> using one
+        /// of its constructors and then calling
+        /// <see cref="System.Threading.Tasks.Task.Start()">Start</see> to schedule it for execution.
+        /// However, unless creation and scheduling must be separated, StartNew is the recommended approach
+        /// for both simplicity and performance.
+        /// </remarks>
+        public Task<TResult> StartNew<TResult>(Func<object, TResult> function, object state, TaskCreationOptions creationOptions)
+        {
+            Task currTask = Task.InternalCurrent;
+            return Task<TResult>.StartNew(currTask, function, state, m_defaultCancellationToken,
+                creationOptions, InternalTaskOptions.None, GetDefaultScheduler(currTask));
+        }
+
+        /// <summary>
+        /// Creates and starts a <see cref="T:System.Threading.Tasks.Task{TResult}"/>.
+        /// </summary>
+        /// <typeparam name="TResult">The type of the result available through the
+        /// <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>.
+        /// </typeparam>
+        /// <param name="function">A function delegate that returns the future result to be available through
+        /// the <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</param>
+        /// <param name="state">An object containing data to be used by the <paramref name="function"/>
+        /// delegate.</param>
+        /// <param name="cancellationToken">The <see cref="CancellationToken"/> that will be assigned to the new task.</param>
+        /// <param name="creationOptions">A TaskCreationOptions value that controls the behavior of the
+        /// created
+        /// <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</param>
+        /// <param name="scheduler">The <see
+        /// cref="T:System.Threading.Tasks.TaskScheduler">TaskScheduler</see>
+        /// that is used to schedule the created <see cref="T:System.Threading.Tasks.Task{TResult}">
+        /// Task{TResult}</see>.</param>
+        /// <returns>The started <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref
+        /// name="function"/>
+        /// argument is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the <paramref
+        /// name="scheduler"/>
+        /// argument is null.</exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">The exception that is thrown when the
+        /// <paramref name="creationOptions"/> argument specifies an invalid TaskCreationOptions
+        /// value.</exception>
+        /// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
+        /// has already been disposed.
+        /// </exception>
+        /// <remarks>
+        /// Calling StartNew is functionally equivalent to creating a <see cref="Task{TResult}"/> using one
+        /// of its constructors and then calling
+        /// <see cref="System.Threading.Tasks.Task.Start()">Start</see> to schedule it for execution.
+        /// However, unless creation and scheduling must be separated, StartNew is the recommended approach
+        /// for both simplicity and performance.
+        /// </remarks>
+        public Task<TResult> StartNew<TResult>(Func<object, TResult> function, object state, CancellationToken cancellationToken,
+            TaskCreationOptions creationOptions, TaskScheduler scheduler)
+        {
+            return Task<TResult>.StartNew(
+                Task.InternalCurrentIfAttached(creationOptions), function, state, cancellationToken,
+                creationOptions, InternalTaskOptions.None, scheduler);
+        }
+
+        //
+        // FromAsync methods
+        //
+
+        /// <summary>
+        /// Creates a <see cref="T:System.Threading.Tasks.Task">Task</see> that executes an end method action
+        /// when a specified <see cref="T:System.IAsyncResult">IAsyncResult</see> completes.
+        /// </summary>
+        /// <param name="asyncResult">The IAsyncResult whose completion should trigger the processing of the
+        /// <paramref name="endMethod"/>.</param>
+        /// <param name="endMethod">The action delegate that processes the completed <paramref
+        /// name="asyncResult"/>.</param>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="asyncResult"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="endMethod"/> argument is null.</exception>
+        /// <returns>A <see cref="T:System.Threading.Tasks.Task">Task</see> that represents the asynchronous
+        /// operation.</returns>
+        public Task FromAsync(
+            IAsyncResult asyncResult,
+            Action<IAsyncResult> endMethod)
+        {
+            return FromAsync(asyncResult, endMethod, m_defaultCreationOptions, DefaultScheduler);
+        }
+
+        /// <summary>
+        /// Creates a <see cref="T:System.Threading.Tasks.Task">Task</see> that executes an end method action
+        /// when a specified <see cref="T:System.IAsyncResult">IAsyncResult</see> completes.
+        /// </summary>
+        /// <param name="asyncResult">The IAsyncResult whose completion should trigger the processing of the
+        /// <paramref name="endMethod"/>.</param>
+        /// <param name="endMethod">The action delegate that processes the completed <paramref
+        /// name="asyncResult"/>.</param>
+        /// <param name="creationOptions">The TaskCreationOptions value that controls the behavior of the
+        /// created <see cref="T:System.Threading.Tasks.Task">Task</see>.</param>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="asyncResult"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="endMethod"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">The exception that is thrown when the
+        /// <paramref name="creationOptions"/> argument specifies an invalid TaskCreationOptions
+        /// value.</exception>
+        /// <returns>A <see cref="T:System.Threading.Tasks.Task">Task</see> that represents the asynchronous
+        /// operation.</returns>
+        public Task FromAsync(
+            IAsyncResult asyncResult,
+            Action<IAsyncResult> endMethod,
+            TaskCreationOptions creationOptions)
+        {
+            return FromAsync(asyncResult, endMethod, creationOptions, DefaultScheduler);
+        }
+
+        /// <summary>
+        /// Creates a <see cref="T:System.Threading.Tasks.Task">Task</see> that executes an end method action
+        /// when a specified <see cref="T:System.IAsyncResult">IAsyncResult</see> completes.
+        /// </summary>
+        /// <param name="asyncResult">The IAsyncResult whose completion should trigger the processing of the
+        /// <paramref name="endMethod"/>.</param>
+        /// <param name="endMethod">The action delegate that processes the completed <paramref
+        /// name="asyncResult"/>.</param>
+        /// <param name="scheduler">The <see cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see>
+        /// that is used to schedule the task that executes the end method.</param>
+        /// <param name="creationOptions">The TaskCreationOptions value that controls the behavior of the
+        /// created <see cref="T:System.Threading.Tasks.Task">Task</see>.</param>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="asyncResult"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="endMethod"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="scheduler"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">The exception that is thrown when the
+        /// <paramref name="creationOptions"/> argument specifies an invalid TaskCreationOptions
+        /// value.</exception>
+        /// <returns>A <see cref="T:System.Threading.Tasks.Task">Task</see> that represents the asynchronous
+        /// operation.</returns>
+        public Task FromAsync(
+            IAsyncResult asyncResult,
+            Action<IAsyncResult> endMethod,
+            TaskCreationOptions creationOptions,
+            TaskScheduler scheduler)
+        {
+            return TaskFactory<VoidTaskResult>.FromAsyncImpl(asyncResult, null, endMethod, creationOptions, scheduler);
+        }
+
+        /// <summary>
+        /// Creates a <see cref="T:System.Threading.Tasks.Task">Task</see> that represents a pair of begin
+        /// and end methods that conform to the Asynchronous Programming Model pattern.
+        /// </summary>
+        /// <param name="beginMethod">The delegate that begins the asynchronous operation.</param>
+        /// <param name="endMethod">The delegate that ends the asynchronous operation.</param>
+        /// <param name="state">An object containing data to be used by the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="beginMethod"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="endMethod"/> argument is null.</exception>
+        /// <returns>The created <see cref="T:System.Threading.Tasks.Task">Task</see> that represents the
+        /// asynchronous operation.</returns>
+        /// <remarks>
+        /// This method throws any exceptions thrown by the <paramref name="beginMethod"/>.
+        /// </remarks>
+        public Task FromAsync(
+            Func<AsyncCallback, object, IAsyncResult> beginMethod,
+            Action<IAsyncResult> endMethod,
+            object state)
+        {
+            return FromAsync(beginMethod, endMethod, state, m_defaultCreationOptions);
+        }
+
+        /// <summary>
+        /// Creates a <see cref="T:System.Threading.Tasks.Task">Task</see> that represents a pair of begin
+        /// and end methods that conform to the Asynchronous Programming Model pattern.
+        /// </summary>
+        /// <param name="beginMethod">The delegate that begins the asynchronous operation.</param>
+        /// <param name="endMethod">The delegate that ends the asynchronous operation.</param>
+        /// <param name="creationOptions">The TaskCreationOptions value that controls the behavior of the
+        /// created <see cref="T:System.Threading.Tasks.Task">Task</see>.</param>
+        /// <param name="state">An object containing data to be used by the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="beginMethod"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="endMethod"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">The exception that is thrown when the
+        /// <paramref name="creationOptions"/> argument specifies an invalid TaskCreationOptions
+        /// value.</exception>
+        /// <returns>The created <see cref="T:System.Threading.Tasks.Task">Task</see> that represents the
+        /// asynchronous operation.</returns>
+        /// <remarks>
+        /// This method throws any exceptions thrown by the <paramref name="beginMethod"/>.
+        /// </remarks>
+        public Task FromAsync(
+            Func<AsyncCallback, object, IAsyncResult> beginMethod,
+            Action<IAsyncResult> endMethod, object state, TaskCreationOptions creationOptions)
+        {
+            return TaskFactory<VoidTaskResult>.FromAsyncImpl(beginMethod, null, endMethod, state, creationOptions);
+        }
+
+        /// <summary>
+        /// Creates a <see cref="T:System.Threading.Tasks.Task">Task</see> that represents a pair of begin
+        /// and end methods that conform to the Asynchronous Programming Model pattern.
+        /// </summary>
+        /// <typeparam name="TArg1">The type of the first argument passed to the <paramref
+        /// name="beginMethod"/>
+        /// delegate.</typeparam>
+        /// <param name="beginMethod">The delegate that begins the asynchronous operation.</param>
+        /// <param name="endMethod">The delegate that ends the asynchronous operation.</param>
+        /// <param name="arg1">The first argument passed to the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <param name="state">An object containing data to be used by the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="beginMethod"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="endMethod"/> argument is null.</exception>
+        /// <returns>The created <see cref="T:System.Threading.Tasks.Task">Task</see> that represents the
+        /// asynchronous operation.</returns>
+        /// <remarks>
+        /// This method throws any exceptions thrown by the <paramref name="beginMethod"/>.
+        /// </remarks>
+        public Task FromAsync<TArg1>(
+            Func<TArg1, AsyncCallback, object, IAsyncResult> beginMethod,
+            Action<IAsyncResult> endMethod,
+            TArg1 arg1,
+            object state)
+        {
+            return FromAsync(beginMethod, endMethod, arg1, state, m_defaultCreationOptions);
+        }
+
+        /// <summary>
+        /// Creates a <see cref="T:System.Threading.Tasks.Task">Task</see> that represents a pair of begin
+        /// and end methods that conform to the Asynchronous Programming Model pattern.
+        /// </summary>
+        /// <typeparam name="TArg1">The type of the first argument passed to the <paramref
+        /// name="beginMethod"/>
+        /// delegate.</typeparam>
+        /// <param name="beginMethod">The delegate that begins the asynchronous operation.</param>
+        /// <param name="endMethod">The delegate that ends the asynchronous operation.</param>
+        /// <param name="arg1">The first argument passed to the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <param name="creationOptions">The TaskCreationOptions value that controls the behavior of the
+        /// created <see cref="T:System.Threading.Tasks.Task">Task</see>.</param>
+        /// <param name="state">An object containing data to be used by the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="beginMethod"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="endMethod"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">The exception that is thrown when the
+        /// <paramref name="creationOptions"/> argument specifies an invalid TaskCreationOptions
+        /// value.</exception>
+        /// <returns>The created <see cref="T:System.Threading.Tasks.Task">Task</see> that represents the
+        /// asynchronous operation.</returns>
+        /// <remarks>
+        /// This method throws any exceptions thrown by the <paramref name="beginMethod"/>.
+        /// </remarks>
+        public Task FromAsync<TArg1>(
+            Func<TArg1, AsyncCallback, object, IAsyncResult> beginMethod,
+            Action<IAsyncResult> endMethod,
+            TArg1 arg1, object state, TaskCreationOptions creationOptions)
+        {
+            return TaskFactory<VoidTaskResult>.FromAsyncImpl(beginMethod, null, endMethod, arg1, state, creationOptions);
+        }
+
+        /// <summary>
+        /// Creates a <see cref="T:System.Threading.Tasks.Task">Task</see> that represents a pair of begin
+        /// and end methods that conform to the Asynchronous Programming Model pattern.
+        /// </summary>
+        /// <typeparam name="TArg1">The type of the first argument passed to the <paramref
+        /// name="beginMethod"/>
+        /// delegate.</typeparam>
+        /// <typeparam name="TArg2">The type of the second argument passed to <paramref name="beginMethod"/>
+        /// delegate.</typeparam>
+        /// <param name="beginMethod">The delegate that begins the asynchronous operation.</param>
+        /// <param name="endMethod">The delegate that ends the asynchronous operation.</param>
+        /// <param name="arg1">The first argument passed to the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <param name="arg2">The second argument passed to the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <param name="state">An object containing data to be used by the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="beginMethod"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="endMethod"/> argument is null.</exception>
+        /// <returns>The created <see cref="T:System.Threading.Tasks.Task">Task</see> that represents the
+        /// asynchronous operation.</returns>
+        /// <remarks>
+        /// This method throws any exceptions thrown by the <paramref name="beginMethod"/>.
+        /// </remarks>
+        public Task FromAsync<TArg1, TArg2>(
+            Func<TArg1, TArg2, AsyncCallback, object, IAsyncResult> beginMethod,
+            Action<IAsyncResult> endMethod,
+            TArg1 arg1, TArg2 arg2, object state)
+        {
+            return FromAsync(beginMethod, endMethod, arg1, arg2, state, m_defaultCreationOptions);
+        }
+
+        /// <summary>
+        /// Creates a <see cref="T:System.Threading.Tasks.Task">Task</see> that represents a pair of begin
+        /// and end methods that conform to the Asynchronous Programming Model pattern.
+        /// </summary>
+        /// <typeparam name="TArg1">The type of the first argument passed to the <paramref
+        /// name="beginMethod"/>
+        /// delegate.</typeparam>
+        /// <typeparam name="TArg2">The type of the second argument passed to <paramref name="beginMethod"/>
+        /// delegate.</typeparam>
+        /// <param name="beginMethod">The delegate that begins the asynchronous operation.</param>
+        /// <param name="endMethod">The delegate that ends the asynchronous operation.</param>
+        /// <param name="arg1">The first argument passed to the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <param name="arg2">The second argument passed to the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <param name="creationOptions">The TaskCreationOptions value that controls the behavior of the
+        /// created <see cref="T:System.Threading.Tasks.Task">Task</see>.</param>
+        /// <param name="state">An object containing data to be used by the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="beginMethod"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="endMethod"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">The exception that is thrown when the
+        /// <paramref name="creationOptions"/> argument specifies an invalid TaskCreationOptions
+        /// value.</exception>
+        /// <returns>The created <see cref="T:System.Threading.Tasks.Task">Task</see> that represents the
+        /// asynchronous operation.</returns>
+        /// <remarks>
+        /// This method throws any exceptions thrown by the <paramref name="beginMethod"/>.
+        /// </remarks>
+        public Task FromAsync<TArg1, TArg2>(
+            Func<TArg1, TArg2, AsyncCallback, object, IAsyncResult> beginMethod,
+            Action<IAsyncResult> endMethod,
+            TArg1 arg1, TArg2 arg2, object state, TaskCreationOptions creationOptions)
+        {
+            return TaskFactory<VoidTaskResult>.FromAsyncImpl(beginMethod, null, endMethod, arg1, arg2, state, creationOptions);
+        }
+
+        /// <summary>
+        /// Creates a <see cref="T:System.Threading.Tasks.Task">Task</see> that represents a pair of begin
+        /// and end methods that conform to the Asynchronous Programming Model pattern.
+        /// </summary>
+        /// <typeparam name="TArg1">The type of the first argument passed to the <paramref
+        /// name="beginMethod"/>
+        /// delegate.</typeparam>
+        /// <typeparam name="TArg2">The type of the second argument passed to <paramref name="beginMethod"/>
+        /// delegate.</typeparam>
+        /// <typeparam name="TArg3">The type of the third argument passed to <paramref name="beginMethod"/>
+        /// delegate.</typeparam>
+        /// <param name="beginMethod">The delegate that begins the asynchronous operation.</param>
+        /// <param name="endMethod">The delegate that ends the asynchronous operation.</param>
+        /// <param name="arg1">The first argument passed to the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <param name="arg2">The second argument passed to the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <param name="arg3">The third argument passed to the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <param name="state">An object containing data to be used by the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="beginMethod"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="endMethod"/> argument is null.</exception>
+        /// <returns>The created <see cref="T:System.Threading.Tasks.Task">Task</see> that represents the
+        /// asynchronous operation.</returns>
+        /// <remarks>
+        /// This method throws any exceptions thrown by the <paramref name="beginMethod"/>.
+        /// </remarks>
+        public Task FromAsync<TArg1, TArg2, TArg3>(
+            Func<TArg1, TArg2, TArg3, AsyncCallback, object, IAsyncResult> beginMethod,
+            Action<IAsyncResult> endMethod,
+            TArg1 arg1, TArg2 arg2, TArg3 arg3, object state)
+        {
+            return FromAsync(beginMethod, endMethod, arg1, arg2, arg3, state, m_defaultCreationOptions);
+        }
+
+        /// <summary>
+        /// Creates a <see cref="T:System.Threading.Tasks.Task">Task</see> that represents a pair of begin
+        /// and end methods that conform to the Asynchronous Programming Model pattern.
+        /// </summary>
+        /// <typeparam name="TArg1">The type of the first argument passed to the <paramref
+        /// name="beginMethod"/>
+        /// delegate.</typeparam>
+        /// <typeparam name="TArg2">The type of the second argument passed to <paramref name="beginMethod"/>
+        /// delegate.</typeparam>
+        /// <typeparam name="TArg3">The type of the third argument passed to <paramref name="beginMethod"/>
+        /// delegate.</typeparam>
+        /// <param name="beginMethod">The delegate that begins the asynchronous operation.</param>
+        /// <param name="endMethod">The delegate that ends the asynchronous operation.</param>
+        /// <param name="arg1">The first argument passed to the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <param name="arg2">The second argument passed to the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <param name="arg3">The third argument passed to the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <param name="creationOptions">The TaskCreationOptions value that controls the behavior of the
+        /// created <see cref="T:System.Threading.Tasks.Task">Task</see>.</param>
+        /// <param name="state">An object containing data to be used by the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="beginMethod"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="endMethod"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">The exception that is thrown when the
+        /// <paramref name="creationOptions"/> argument specifies an invalid TaskCreationOptions
+        /// value.</exception>
+        /// <returns>The created <see cref="T:System.Threading.Tasks.Task">Task</see> that represents the
+        /// asynchronous operation.</returns>
+        /// <remarks>
+        /// This method throws any exceptions thrown by the <paramref name="beginMethod"/>.
+        /// </remarks>
+        public Task FromAsync<TArg1, TArg2, TArg3>(
+            Func<TArg1, TArg2, TArg3, AsyncCallback, object, IAsyncResult> beginMethod,
+            Action<IAsyncResult> endMethod,
+            TArg1 arg1, TArg2 arg2, TArg3 arg3, object state, TaskCreationOptions creationOptions)
+        {
+            return TaskFactory<VoidTaskResult>.FromAsyncImpl<TArg1, TArg2, TArg3>(beginMethod, null, endMethod, arg1, arg2, arg3, state, creationOptions);
+        }
+
+        //
+        // Additional FromAsync() overloads used for inferencing convenience
+        //
+
+        /// <summary>
+        /// Creates a <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see> that executes an end
+        /// method function when a specified <see cref="T:System.IAsyncResult">IAsyncResult</see> completes.
+        /// </summary>
+        /// <typeparam name="TResult">The type of the result available through the
+        /// <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>.
+        /// </typeparam>
+        /// <param name="asyncResult">The IAsyncResult whose completion should trigger the processing of the
+        /// <paramref name="endMethod"/>.</param>
+        /// <param name="endMethod">The function delegate that processes the completed <paramref
+        /// name="asyncResult"/>.</param>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="asyncResult"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="endMethod"/> argument is null.</exception>
+        /// <returns>A <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see> that represents the
+        /// asynchronous operation.</returns>
+        public Task<TResult> FromAsync<TResult>(
+            IAsyncResult asyncResult, Func<IAsyncResult, TResult> endMethod)
+        {
+            return TaskFactory<TResult>.FromAsyncImpl(asyncResult, endMethod, null, m_defaultCreationOptions, DefaultScheduler);
+        }
+
+        /// <summary>
+        /// Creates a <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see> that executes an end
+        /// method function when a specified <see cref="T:System.IAsyncResult">IAsyncResult</see> completes.
+        /// </summary>
+        /// <typeparam name="TResult">The type of the result available through the
+        /// <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>.
+        /// </typeparam>
+        /// <param name="asyncResult">The IAsyncResult whose completion should trigger the processing of the
+        /// <paramref name="endMethod"/>.</param>
+        /// <param name="endMethod">The function delegate that processes the completed <paramref
+        /// name="asyncResult"/>.</param>
+        /// <param name="creationOptions">The TaskCreationOptions value that controls the behavior of the
+        /// created <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>.</param>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="asyncResult"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="endMethod"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">The exception that is thrown when the
+        /// <paramref name="creationOptions"/> argument specifies an invalid TaskCreationOptions
+        /// value.</exception>
+        /// <returns>A <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see> that represents the
+        /// asynchronous operation.</returns>
+        public Task<TResult> FromAsync<TResult>(
+            IAsyncResult asyncResult, Func<IAsyncResult, TResult> endMethod, TaskCreationOptions creationOptions)
+        {
+            return TaskFactory<TResult>.FromAsyncImpl(asyncResult, endMethod, null, creationOptions, DefaultScheduler);
+        }
+
+        /// <summary>
+        /// Creates a <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see> that executes an end
+        /// method function when a specified <see cref="T:System.IAsyncResult">IAsyncResult</see> completes.
+        /// </summary>
+        /// <typeparam name="TResult">The type of the result available through the
+        /// <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>.
+        /// </typeparam>
+        /// <param name="asyncResult">The IAsyncResult whose completion should trigger the processing of the
+        /// <paramref name="endMethod"/>.</param>
+        /// <param name="endMethod">The function delegate that processes the completed <paramref
+        /// name="asyncResult"/>.</param>
+        /// <param name="scheduler">The <see cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see>
+        /// that is used to schedule the task that executes the end method.</param>
+        /// <param name="creationOptions">The TaskCreationOptions value that controls the behavior of the
+        /// created <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>.</param>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="asyncResult"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="endMethod"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="scheduler"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">The exception that is thrown when the
+        /// <paramref name="creationOptions"/> argument specifies an invalid TaskCreationOptions
+        /// value.</exception>
+        /// <returns>A <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see> that represents the
+        /// asynchronous operation.</returns>
+        public Task<TResult> FromAsync<TResult>(
+            IAsyncResult asyncResult, Func<IAsyncResult, TResult> endMethod, TaskCreationOptions creationOptions, TaskScheduler scheduler)
+        {
+            return TaskFactory<TResult>.FromAsyncImpl(asyncResult, endMethod, null, creationOptions, scheduler);
+        }
+
+        /// <summary>
+        /// Creates a <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see> that represents a pair of
+        /// begin and end methods that conform to the Asynchronous Programming Model pattern.
+        /// </summary>
+        /// <typeparam name="TResult">The type of the result available through the
+        /// <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>.
+        /// </typeparam>
+        /// <param name="beginMethod">The delegate that begins the asynchronous operation.</param>
+        /// <param name="endMethod">The delegate that ends the asynchronous operation.</param>
+        /// <param name="state">An object containing data to be used by the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="beginMethod"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="endMethod"/> argument is null.</exception>
+        /// <returns>The created <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see> that
+        /// represents the asynchronous operation.</returns>
+        /// <remarks>
+        /// This method throws any exceptions thrown by the <paramref name="beginMethod"/>.
+        /// </remarks>
+        public Task<TResult> FromAsync<TResult>(
+            Func<AsyncCallback, object, IAsyncResult> beginMethod,
+            Func<IAsyncResult, TResult> endMethod, object state)
+        {
+            return TaskFactory<TResult>.FromAsyncImpl(beginMethod, endMethod, null, state, m_defaultCreationOptions);
+        }
+
+        /// <summary>
+        /// Creates a <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see> that represents a pair of
+        /// begin and end methods that conform to the Asynchronous Programming Model pattern.
+        /// </summary>
+        /// <typeparam name="TResult">The type of the result available through the
+        /// <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>.
+        /// </typeparam>
+        /// <param name="beginMethod">The delegate that begins the asynchronous operation.</param>
+        /// <param name="endMethod">The delegate that ends the asynchronous operation.</param>
+        /// <param name="creationOptions">The TaskCreationOptions value that controls the behavior of the
+        /// created <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>.</param>
+        /// <param name="state">An object containing data to be used by the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="beginMethod"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="endMethod"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">The exception that is thrown when the
+        /// <paramref name="creationOptions"/> argument specifies an invalid TaskCreationOptions
+        /// value.</exception>
+        /// <returns>The created <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see> that
+        /// represents the asynchronous operation.</returns>
+        /// <remarks>
+        /// This method throws any exceptions thrown by the <paramref name="beginMethod"/>.
+        /// </remarks>
+        public Task<TResult> FromAsync<TResult>(
+            Func<AsyncCallback, object, IAsyncResult> beginMethod,
+            Func<IAsyncResult, TResult> endMethod, object state, TaskCreationOptions creationOptions)
+        {
+            return TaskFactory<TResult>.FromAsyncImpl(beginMethod, endMethod, null, state, creationOptions);
+        }
+
+        /// <summary>
+        /// Creates a <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see> that represents a pair of
+        /// begin and end methods that conform to the Asynchronous Programming Model pattern.
+        /// </summary>
+        /// <typeparam name="TArg1">The type of the first argument passed to the <paramref
+        /// name="beginMethod"/> delegate.</typeparam>
+        /// <typeparam name="TResult">The type of the result available through the
+        /// <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>.
+        /// </typeparam>
+        /// <param name="beginMethod">The delegate that begins the asynchronous operation.</param>
+        /// <param name="endMethod">The delegate that ends the asynchronous operation.</param>
+        /// <param name="arg1">The first argument passed to the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <param name="state">An object containing data to be used by the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="beginMethod"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="endMethod"/> argument is null.</exception>
+        /// <returns>The created <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see> that
+        /// represents the asynchronous operation.</returns>
+        /// <remarks>
+        /// This method throws any exceptions thrown by the <paramref name="beginMethod"/>.
+        /// </remarks>
+        public Task<TResult> FromAsync<TArg1, TResult>(
+            Func<TArg1, AsyncCallback, object, IAsyncResult> beginMethod,
+            Func<IAsyncResult, TResult> endMethod, TArg1 arg1, object state)
+        {
+            return TaskFactory<TResult>.FromAsyncImpl(beginMethod, endMethod, null, arg1, state, m_defaultCreationOptions);
+        }
+
+        /// <summary>
+        /// Creates a <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see> that represents a pair of
+        /// begin and end methods that conform to the Asynchronous Programming Model pattern.
+        /// </summary>
+        /// <typeparam name="TArg1">The type of the first argument passed to the <paramref
+        /// name="beginMethod"/> delegate.</typeparam>
+        /// <typeparam name="TResult">The type of the result available through the
+        /// <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>.
+        /// </typeparam>
+        /// <param name="beginMethod">The delegate that begins the asynchronous operation.</param>
+        /// <param name="endMethod">The delegate that ends the asynchronous operation.</param>
+        /// <param name="arg1">The first argument passed to the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <param name="creationOptions">The TaskCreationOptions value that controls the behavior of the
+        /// created <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>.</param>
+        /// <param name="state">An object containing data to be used by the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="beginMethod"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="endMethod"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">The exception that is thrown when the
+        /// <paramref name="creationOptions"/> argument specifies an invalid TaskCreationOptions
+        /// value.</exception>
+        /// <returns>The created <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see> that
+        /// represents the asynchronous operation.</returns>
+        /// <remarks>
+        /// This method throws any exceptions thrown by the <paramref name="beginMethod"/>.
+        /// </remarks>
+        public Task<TResult> FromAsync<TArg1, TResult>(Func<TArg1, AsyncCallback, object, IAsyncResult> beginMethod,
+            Func<IAsyncResult, TResult> endMethod, TArg1 arg1, object state, TaskCreationOptions creationOptions)
+        {
+            return TaskFactory<TResult>.FromAsyncImpl(beginMethod, endMethod, null, arg1, state, creationOptions);
+        }
+
+        /// <summary>
+        /// Creates a <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see> that represents a pair of
+        /// begin and end methods that conform to the Asynchronous Programming Model pattern.
+        /// </summary>
+        /// <typeparam name="TArg1">The type of the first argument passed to the <paramref
+        /// name="beginMethod"/> delegate.</typeparam>
+        /// <typeparam name="TArg2">The type of the second argument passed to <paramref name="beginMethod"/>
+        /// delegate.</typeparam>
+        /// <typeparam name="TResult">The type of the result available through the
+        /// <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>.
+        /// </typeparam>
+        /// <param name="beginMethod">The delegate that begins the asynchronous operation.</param>
+        /// <param name="endMethod">The delegate that ends the asynchronous operation.</param>
+        /// <param name="arg1">The first argument passed to the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <param name="arg2">The second argument passed to the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <param name="state">An object containing data to be used by the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="beginMethod"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="endMethod"/> argument is null.</exception>
+        /// <returns>The created <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see> that
+        /// represents the asynchronous operation.</returns>
+        /// <remarks>
+        /// This method throws any exceptions thrown by the <paramref name="beginMethod"/>.
+        /// </remarks>
+        public Task<TResult> FromAsync<TArg1, TArg2, TResult>(Func<TArg1, TArg2, AsyncCallback, object, IAsyncResult> beginMethod,
+            Func<IAsyncResult, TResult> endMethod, TArg1 arg1, TArg2 arg2, object state)
+        {
+            return TaskFactory<TResult>.FromAsyncImpl(beginMethod, endMethod, null, arg1, arg2, state, m_defaultCreationOptions);
+        }
+
+        /// <summary>
+        /// Creates a <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see> that represents a pair of
+        /// begin and end methods that conform to the Asynchronous Programming Model pattern.
+        /// </summary>
+        /// <typeparam name="TArg1">The type of the first argument passed to the <paramref
+        /// name="beginMethod"/> delegate.</typeparam>
+        /// <typeparam name="TArg2">The type of the second argument passed to <paramref name="beginMethod"/>
+        /// delegate.</typeparam>
+        /// <typeparam name="TResult">The type of the result available through the
+        /// <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>.
+        /// </typeparam>
+        /// <param name="beginMethod">The delegate that begins the asynchronous operation.</param>
+        /// <param name="endMethod">The delegate that ends the asynchronous operation.</param>
+        /// <param name="arg1">The first argument passed to the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <param name="arg2">The second argument passed to the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <param name="creationOptions">The TaskCreationOptions value that controls the behavior of the
+        /// created <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>.</param>
+        /// <param name="state">An object containing data to be used by the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="beginMethod"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="endMethod"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">The exception that is thrown when the
+        /// <paramref name="creationOptions"/> argument specifies an invalid TaskCreationOptions
+        /// value.</exception>
+        /// <returns>The created <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see> that
+        /// represents the asynchronous operation.</returns>
+        /// <remarks>
+        /// This method throws any exceptions thrown by the <paramref name="beginMethod"/>.
+        /// </remarks>
+        public Task<TResult> FromAsync<TArg1, TArg2, TResult>(
+            Func<TArg1, TArg2, AsyncCallback, object, IAsyncResult> beginMethod,
+            Func<IAsyncResult, TResult> endMethod, TArg1 arg1, TArg2 arg2, object state, TaskCreationOptions creationOptions)
+        {
+            return TaskFactory<TResult>.FromAsyncImpl(beginMethod, endMethod, null, arg1, arg2, state, creationOptions);
+        }
+
+        /// <summary>
+        /// Creates a <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see> that represents a pair of
+        /// begin and end methods that conform to the Asynchronous Programming Model pattern.
+        /// </summary>
+        /// <typeparam name="TArg1">The type of the first argument passed to the <paramref
+        /// name="beginMethod"/> delegate.</typeparam>
+        /// <typeparam name="TArg2">The type of the second argument passed to <paramref name="beginMethod"/>
+        /// delegate.</typeparam>
+        /// <typeparam name="TArg3">The type of the third argument passed to <paramref name="beginMethod"/>
+        /// delegate.</typeparam>
+        /// <typeparam name="TResult">The type of the result available through the
+        /// <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>.
+        /// </typeparam>
+        /// <param name="beginMethod">The delegate that begins the asynchronous operation.</param>
+        /// <param name="endMethod">The delegate that ends the asynchronous operation.</param>
+        /// <param name="arg1">The first argument passed to the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <param name="arg2">The second argument passed to the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <param name="arg3">The third argument passed to the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <param name="state">An object containing data to be used by the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="beginMethod"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="endMethod"/> argument is null.</exception>
+        /// <returns>The created <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see> that
+        /// represents the asynchronous operation.</returns>
+        /// <remarks>
+        /// This method throws any exceptions thrown by the <paramref name="beginMethod"/>.
+        /// </remarks>
+        public Task<TResult> FromAsync<TArg1, TArg2, TArg3, TResult>(
+            Func<TArg1, TArg2, TArg3, AsyncCallback, object, IAsyncResult> beginMethod,
+            Func<IAsyncResult, TResult> endMethod, TArg1 arg1, TArg2 arg2, TArg3 arg3, object state)
+        {
+            return TaskFactory<TResult>.FromAsyncImpl(beginMethod, endMethod, null, arg1, arg2, arg3, state, m_defaultCreationOptions);
+        }
+
+        /// <summary>
+        /// Creates a <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see> that represents a pair of
+        /// begin and end methods that conform to the Asynchronous Programming Model pattern.
+        /// </summary>
+        /// <typeparam name="TArg1">The type of the first argument passed to the <paramref
+        /// name="beginMethod"/> delegate.</typeparam>
+        /// <typeparam name="TArg2">The type of the second argument passed to <paramref name="beginMethod"/>
+        /// delegate.</typeparam>
+        /// <typeparam name="TArg3">The type of the third argument passed to <paramref name="beginMethod"/>
+        /// delegate.</typeparam>
+        /// <typeparam name="TResult">The type of the result available through the
+        /// <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>.
+        /// </typeparam>
+        /// <param name="beginMethod">The delegate that begins the asynchronous operation.</param>
+        /// <param name="endMethod">The delegate that ends the asynchronous operation.</param>
+        /// <param name="arg1">The first argument passed to the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <param name="arg2">The second argument passed to the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <param name="arg3">The third argument passed to the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <param name="creationOptions">The TaskCreationOptions value that controls the behavior of the
+        /// created <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>.</param>
+        /// <param name="state">An object containing data to be used by the <paramref name="beginMethod"/>
+        /// delegate.</param>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="beginMethod"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="endMethod"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">The exception that is thrown when the
+        /// <paramref name="creationOptions"/> argument specifies an invalid TaskCreationOptions
+        /// value.</exception>
+        /// <returns>The created <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see> that
+        /// represents the asynchronous operation.</returns>
+        /// <remarks>
+        /// This method throws any exceptions thrown by the <paramref name="beginMethod"/>.
+        /// </remarks>
+        public Task<TResult> FromAsync<TArg1, TArg2, TArg3, TResult>(
+            Func<TArg1, TArg2, TArg3, AsyncCallback, object, IAsyncResult> beginMethod,
+            Func<IAsyncResult, TResult> endMethod, TArg1 arg1, TArg2 arg2, TArg3 arg3, object state, TaskCreationOptions creationOptions)
+        {
+            return TaskFactory<TResult>.FromAsyncImpl(beginMethod, endMethod, null, arg1, arg2, arg3, state, creationOptions);
+        }
+
+        /// <summary>
+        /// Check validity of options passed to FromAsync method
+        /// </summary>
+        /// <param name="creationOptions">The options to be validated.</param>
+        /// <param name="hasBeginMethod">determines type of FromAsync method that called this method</param>
+        internal static void CheckFromAsyncOptions(TaskCreationOptions creationOptions, bool hasBeginMethod)
+        {
+            if (hasBeginMethod)
+            {
+                // Options detected here cause exceptions in FromAsync methods that take beginMethod as a parameter
+                if ((creationOptions & TaskCreationOptions.LongRunning) != 0)
+                    throw new ArgumentOutOfRangeException(nameof(creationOptions), SR.Task_FromAsync_LongRunning);
+                if ((creationOptions & TaskCreationOptions.PreferFairness) != 0)
+                    throw new ArgumentOutOfRangeException(nameof(creationOptions), SR.Task_FromAsync_PreferFairness);
+            }
+
+            // Check for general validity of options
+            if ((creationOptions &
+                    ~(TaskCreationOptions.AttachedToParent |
+                      TaskCreationOptions.DenyChildAttach |
+                      TaskCreationOptions.HideScheduler |
+                      TaskCreationOptions.PreferFairness |
+                      TaskCreationOptions.LongRunning)) != 0)
+            {
+                ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.creationOptions);
+            }
+        }
+
+
+        //
+        // ContinueWhenAll methods
+        //
+
+        // A Task<Task[]> that, given an initial collection of N tasks, will complete when
+        // it has been invoked N times.  This allows us to replace this logic:
+        //      Task<Task[]> promise = new Task<Task[]>(...);
+        //      int _count = tasksCopy.Length;
+        //      Action<Task> completionAction = delegate {if(Interlocked.Decrement(ref _count) == 0) promise.TrySetResult(tasksCopy);
+        //      for(int i=0; i<_count; i++)
+        //          tasksCopy[i].AddCompletionAction(completionAction);
+        // with this logic:
+        //      CompletionOnCountdownPromise promise = new CompletionOnCountdownPromise(tasksCopy);
+        //      for(int i=0; i<tasksCopy.Length; i++) tasksCopy[i].AddCompletionAction(promise);
+        // which saves a few allocations.
+        //
+        // Used in TaskFactory.CommonCWAllLogic(Task[]), below.
+        private sealed class CompleteOnCountdownPromise : Task<Task[]>, ITaskCompletionAction
+        {
+            private readonly Task[] _tasks;
+            private int _count;
+
+            internal CompleteOnCountdownPromise(Task[] tasksCopy) : base()
+            {
+                Debug.Assert((tasksCopy != null) && (tasksCopy.Length > 0), "Expected non-null task array with at least one element in it");
+                _tasks = tasksCopy;
+                _count = tasksCopy.Length;
+
+                if (DebuggerSupport.LoggingOn)
+                    DebuggerSupport.TraceOperationCreation(CausalityTraceLevel.Required, this, "TaskFactory.ContinueWhenAll", 0);
+                DebuggerSupport.AddToActiveTasks(this);
+            }
+
+            public void Invoke(Task completingTask)
+            {
+                if (DebuggerSupport.LoggingOn)
+                    DebuggerSupport.TraceOperationRelation(CausalityTraceLevel.Important, this, CausalityRelation.Join);
+
+                if (completingTask.IsWaitNotificationEnabled) this.SetNotificationForWaitCompletion(enabled: true);
+                if (Interlocked.Decrement(ref _count) == 0)
+                {
+                    if (DebuggerSupport.LoggingOn)
+                        DebuggerSupport.TraceOperationCompletion(CausalityTraceLevel.Required, this, AsyncStatus.Completed);
+                    DebuggerSupport.RemoveFromActiveTasks(this);
+
+                    TrySetResult(_tasks);
+                }
+                Debug.Assert(_count >= 0, "Count should never go below 0");
+            }
+
+            public bool InvokeMayRunArbitraryCode { get { return true; } }
+
+            /// <summary>
+            /// Returns whether we should notify the debugger of a wait completion.  This returns 
+            /// true iff at least one constituent task has its bit set.
+            /// </summary>
+            internal override bool ShouldNotifyDebuggerOfWaitCompletion
+            {
+                get
+                {
+                    return
+                        base.ShouldNotifyDebuggerOfWaitCompletion &&
+                        Task.AnyTaskRequiresNotifyDebuggerOfWaitCompletion(_tasks);
+                }
+            }
+        }
+
+        // Performs some logic common to all ContinueWhenAll() overloads
+        internal static Task<Task[]> CommonCWAllLogic(Task[] tasksCopy)
+        {
+            Debug.Assert(tasksCopy != null);
+
+            // Create a promise task to be returned to the user
+            CompleteOnCountdownPromise promise = new CompleteOnCountdownPromise(tasksCopy);
+
+            for (int i = 0; i < tasksCopy.Length; i++)
+            {
+                if (tasksCopy[i].IsCompleted) promise.Invoke(tasksCopy[i]); // Short-circuit the completion action, if possible
+                else tasksCopy[i].AddCompletionAction(promise); // simple completion action
+            }
+
+            return promise;
+        }
+
+
+        // A Task<Task<T>[]> that, given an initial collection of N tasks, will complete when
+        // it has been invoked N times.  See comments for non-generic CompleteOnCountdownPromise class.
+        //
+        // Used in TaskFactory.CommonCWAllLogic<TResult>(Task<TResult>[]), below.
+        private sealed class CompleteOnCountdownPromise<T> : Task<Task<T>[]>, ITaskCompletionAction
+        {
+            private readonly Task<T>[] _tasks;
+            private int _count;
+
+            internal CompleteOnCountdownPromise(Task<T>[] tasksCopy) : base()
+            {
+                Debug.Assert((tasksCopy != null) && (tasksCopy.Length > 0), "Expected non-null task array with at least one element in it");
+                _tasks = tasksCopy;
+                _count = tasksCopy.Length;
+
+                if (DebuggerSupport.LoggingOn)
+                    DebuggerSupport.TraceOperationCreation(CausalityTraceLevel.Required, this, "TaskFactory.ContinueWhenAll<>", 0);
+                DebuggerSupport.AddToActiveTasks(this);
+            }
+
+            public void Invoke(Task completingTask)
+            {
+                if (DebuggerSupport.LoggingOn)
+                    DebuggerSupport.TraceOperationRelation(CausalityTraceLevel.Important, this, CausalityRelation.Join);
+
+                if (completingTask.IsWaitNotificationEnabled) this.SetNotificationForWaitCompletion(enabled: true);
+                if (Interlocked.Decrement(ref _count) == 0)
+                {
+                    if (DebuggerSupport.LoggingOn)
+                        DebuggerSupport.TraceOperationCompletion(CausalityTraceLevel.Required, this, AsyncStatus.Completed);
+                    DebuggerSupport.RemoveFromActiveTasks(this);
+
+                    TrySetResult(_tasks);
+                }
+                Debug.Assert(_count >= 0, "Count should never go below 0");
+            }
+
+            public bool InvokeMayRunArbitraryCode { get { return true; } }
+
+            /// <summary>
+            /// Returns whether we should notify the debugger of a wait completion.  This returns 
+            /// true iff at least one constituent task has its bit set.
+            /// </summary>
+            internal override bool ShouldNotifyDebuggerOfWaitCompletion
+            {
+                get
+                {
+                    return
+                        base.ShouldNotifyDebuggerOfWaitCompletion &&
+                        Task.AnyTaskRequiresNotifyDebuggerOfWaitCompletion(_tasks);
+                }
+            }
+        }
+
+
+        internal static Task<Task<T>[]> CommonCWAllLogic<T>(Task<T>[] tasksCopy)
+        {
+            Debug.Assert(tasksCopy != null);
+
+            // Create a promise task to be returned to the user
+            CompleteOnCountdownPromise<T> promise = new CompleteOnCountdownPromise<T>(tasksCopy);
+
+            for (int i = 0; i < tasksCopy.Length; i++)
+            {
+                if (tasksCopy[i].IsCompleted) promise.Invoke(tasksCopy[i]); // Short-circuit the completion action, if possible
+                else tasksCopy[i].AddCompletionAction(promise); // simple completion action
+            }
+
+            return promise;
+        }
+        /// <summary>
+        /// Creates a continuation <see cref="T:System.Threading.Tasks.Task">Task</see> 
+        /// that will be started upon the completion of a set of provided Tasks.
+        /// </summary>
+        /// <param name="tasks">The array of tasks from which to continue.</param>
+        /// <param name="continuationAction">The action delegate to execute when all tasks in 
+        /// the <paramref name="tasks"/> array have completed.</param>
+        /// <returns>The new continuation <see cref="T:System.Threading.Tasks.Task">Task</see>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the 
+        /// <paramref name="tasks"/> array is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the 
+        /// <paramref name="continuationAction"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the 
+        /// <paramref name="tasks"/> array contains a null value.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the 
+        /// <paramref name="tasks"/> array is empty.</exception>
+        public Task ContinueWhenAll(Task[] tasks, Action<Task[]> continuationAction)
+        {
+            if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction));
+
+            return TaskFactory<VoidTaskResult>.ContinueWhenAllImpl(tasks, null, continuationAction, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler);
+        }
+
+
+        /// <summary>
+        /// Creates a continuation <see cref="T:System.Threading.Tasks.Task">Task</see> 
+        /// that will be started upon the completion of a set of provided Tasks.
+        /// </summary>
+        /// <param name="tasks">The array of tasks from which to continue.</param>
+        /// <param name="continuationAction">The action delegate to execute when all tasks in 
+        /// the <paramref name="tasks"/> array have completed.</param>
+        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken">CancellationToken</see> 
+        /// that will be assigned to the new continuation task.</param>
+        /// <returns>The new continuation <see cref="T:System.Threading.Tasks.Task">Task</see>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the 
+        /// <paramref name="tasks"/> array is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the 
+        /// <paramref name="continuationAction"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the 
+        /// <paramref name="tasks"/> array contains a null value.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the 
+        /// <paramref name="tasks"/> array is empty.</exception>
+        /// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
+        /// has already been disposed.
+        /// </exception>
+        public Task ContinueWhenAll(Task[] tasks, Action<Task[]> continuationAction, CancellationToken cancellationToken)
+        {
+            if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction));
+
+            return TaskFactory<VoidTaskResult>.ContinueWhenAllImpl(tasks, null, continuationAction, m_defaultContinuationOptions, cancellationToken, DefaultScheduler);
+        }
+
+        /// <summary>
+        /// Creates a continuation <see cref="T:System.Threading.Tasks.Task">Task</see>
+        /// that will be started upon the completion of a set of provided Tasks.
+        /// </summary>
+        /// <param name="tasks">The array of tasks from which to continue.</param>
+        /// <param name="continuationAction">The action delegate to execute when all tasks in the <paramref
+        /// name="tasks"/> array have completed.</param>
+        /// <param name="continuationOptions">The <see cref="System.Threading.Tasks.TaskContinuationOptions">
+        /// TaskContinuationOptions</see> value that controls the behavior of
+        /// the created continuation <see cref="T:System.Threading.Tasks.Task">Task</see>.</param>
+        /// <returns>The new continuation <see cref="T:System.Threading.Tasks.Task">Task</see>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="continuationAction"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array contains a null value.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is empty.</exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">The exception that is thrown when the
+        /// <paramref name="continuationOptions"/> argument specifies an invalid TaskContinuationOptions
+        /// value.</exception>
+        /// <remarks>
+        /// The NotOn* and OnlyOn* <see cref="System.Threading.Tasks.TaskContinuationOptions">TaskContinuationOptions</see>, 
+        /// which constrain for which <see cref="System.Threading.Tasks.TaskStatus">TaskStatus</see> states a continuation 
+        /// will be executed, are illegal with ContinueWhenAll.
+        /// </remarks>
+        public Task ContinueWhenAll(Task[] tasks, Action<Task[]> continuationAction, TaskContinuationOptions continuationOptions)
+        {
+            if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction));
+
+            return TaskFactory<VoidTaskResult>.ContinueWhenAllImpl(tasks, null, continuationAction, continuationOptions, m_defaultCancellationToken, DefaultScheduler);
+        }
+
+        /// <summary>
+        /// Creates a continuation <see cref="T:System.Threading.Tasks.Task">Task</see>
+        /// that will be started upon the completion of a set of provided Tasks.
+        /// </summary>
+        /// <param name="tasks">The array of tasks from which to continue.</param>
+        /// <param name="continuationAction">The action delegate to execute when all tasks in the <paramref
+        /// name="tasks"/> array have completed.</param>
+        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken">CancellationToken</see> 
+        /// that will be assigned to the new continuation task.</param>
+        /// <param name="continuationOptions">The <see cref="System.Threading.Tasks.TaskContinuationOptions">
+        /// TaskContinuationOptions</see> value that controls the behavior of
+        /// the created continuation <see cref="T:System.Threading.Tasks.Task">Task</see>.</param>
+        /// <param name="scheduler">The <see cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see>
+        /// that is used to schedule the created continuation <see
+        /// cref="T:System.Threading.Tasks.Task">Task</see>.</param>
+        /// <returns>The new continuation <see cref="T:System.Threading.Tasks.Task">Task</see>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="continuationAction"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="scheduler"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array contains a null value.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is empty.</exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">The exception that is thrown when the
+        /// <paramref name="continuationOptions"/> argument specifies an invalid TaskContinuationOptions
+        /// value.</exception>
+        /// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
+        /// has already been disposed.
+        /// </exception>
+        /// <remarks>
+        /// The NotOn* and OnlyOn* <see cref="System.Threading.Tasks.TaskContinuationOptions">TaskContinuationOptions</see>, 
+        /// which constrain for which <see cref="System.Threading.Tasks.TaskStatus">TaskStatus</see> states a continuation 
+        /// will be executed, are illegal with ContinueWhenAll.
+        /// </remarks>
+        public Task ContinueWhenAll(Task[] tasks, Action<Task[]> continuationAction, CancellationToken cancellationToken,
+            TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
+        {
+            if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction));
+
+            return TaskFactory<VoidTaskResult>.ContinueWhenAllImpl(tasks, null, continuationAction, continuationOptions, cancellationToken, scheduler);
+        }
+
+        /// <summary>
+        /// Creates a continuation <see cref="T:System.Threading.Tasks.Task">Task</see> 
+        /// that will be started upon the completion of a set of provided Tasks.
+        /// </summary>
+        /// <typeparam name="TAntecedentResult">The type of the result of the antecedent <paramref name="tasks"/>.</typeparam>
+        /// <param name="tasks">The array of tasks from which to continue.</param>
+        /// <param name="continuationAction">The action delegate to execute when all tasks in 
+        /// the <paramref name="tasks"/> array have completed.</param>
+        /// <returns>The new continuation <see cref="T:System.Threading.Tasks.Task">Task</see>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the 
+        /// <paramref name="tasks"/> array is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the 
+        /// <paramref name="continuationAction"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the 
+        /// <paramref name="tasks"/> array contains a null value.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the 
+        /// <paramref name="tasks"/> array is empty.</exception>
+        public Task ContinueWhenAll<TAntecedentResult>(Task<TAntecedentResult>[] tasks, Action<Task<TAntecedentResult>[]> continuationAction)
+        {
+            if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction));
+
+            return TaskFactory<VoidTaskResult>.ContinueWhenAllImpl<TAntecedentResult>(tasks, null, continuationAction, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler);
+        }
+
+
+        /// <summary>
+        /// Creates a continuation <see cref="T:System.Threading.Tasks.Task">Task</see> 
+        /// that will be started upon the completion of a set of provided Tasks.
+        /// </summary>
+        /// <typeparam name="TAntecedentResult">The type of the result of the antecedent <paramref name="tasks"/>.</typeparam>
+        /// <param name="tasks">The array of tasks from which to continue.</param>
+        /// <param name="continuationAction">The action delegate to execute when all tasks in 
+        /// the <paramref name="tasks"/> array have completed.</param>
+        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken">CancellationToken</see> 
+        /// that will be assigned to the new continuation task.</param>
+        /// <returns>The new continuation <see cref="T:System.Threading.Tasks.Task">Task</see>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the 
+        /// <paramref name="tasks"/> array is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the 
+        /// <paramref name="continuationAction"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the 
+        /// <paramref name="tasks"/> array contains a null value.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the 
+        /// <paramref name="tasks"/> array is empty.</exception>
+        /// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
+        /// has already been disposed.
+        /// </exception>
+        public Task ContinueWhenAll<TAntecedentResult>(Task<TAntecedentResult>[] tasks, Action<Task<TAntecedentResult>[]> continuationAction,
+            CancellationToken cancellationToken)
+        {
+            if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction));
+
+            return TaskFactory<VoidTaskResult>.ContinueWhenAllImpl<TAntecedentResult>(tasks, null, continuationAction, m_defaultContinuationOptions, cancellationToken, DefaultScheduler);
+        }
+
+        /// <summary>
+        /// Creates a continuation <see cref="T:System.Threading.Tasks.Task">Task</see>
+        /// that will be started upon the completion of a set of provided Tasks.
+        /// </summary>
+        /// <typeparam name="TAntecedentResult">The type of the result of the antecedent <paramref name="tasks"/>.</typeparam>
+        /// <param name="tasks">The array of tasks from which to continue.</param>
+        /// <param name="continuationAction">The action delegate to execute when all tasks in the <paramref
+        /// name="tasks"/> array have completed.</param>
+        /// <param name="continuationOptions">The <see cref="System.Threading.Tasks.TaskContinuationOptions">
+        /// TaskContinuationOptions</see> value that controls the behavior of
+        /// the created continuation <see cref="T:System.Threading.Tasks.Task">Task</see>.</param>
+        /// <returns>The new continuation <see cref="T:System.Threading.Tasks.Task">Task</see>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="continuationAction"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array contains a null value.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is empty.</exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">The exception that is thrown when the
+        /// <paramref name="continuationOptions"/> argument specifies an invalid TaskContinuationOptions
+        /// value.</exception>
+        /// <remarks>
+        /// The NotOn* and OnlyOn* <see cref="System.Threading.Tasks.TaskContinuationOptions">TaskContinuationOptions</see>, 
+        /// which constrain for which <see cref="System.Threading.Tasks.TaskStatus">TaskStatus</see> states a continuation 
+        /// will be executed, are illegal with ContinueWhenAll.
+        /// </remarks>
+        public Task ContinueWhenAll<TAntecedentResult>(Task<TAntecedentResult>[] tasks, Action<Task<TAntecedentResult>[]> continuationAction,
+            TaskContinuationOptions continuationOptions)
+        {
+            if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction));
+
+            return TaskFactory<VoidTaskResult>.ContinueWhenAllImpl<TAntecedentResult>(tasks, null, continuationAction, continuationOptions, m_defaultCancellationToken, DefaultScheduler);
+        }
+
+        /// <summary>
+        /// Creates a continuation <see cref="T:System.Threading.Tasks.Task">Task</see>
+        /// that will be started upon the completion of a set of provided Tasks.
+        /// </summary>
+        /// <typeparam name="TAntecedentResult">The type of the result of the antecedent <paramref name="tasks"/>.</typeparam>
+        /// <param name="tasks">The array of tasks from which to continue.</param>
+        /// <param name="continuationAction">The action delegate to execute when all tasks in the <paramref
+        /// name="tasks"/> array have completed.</param>
+        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken">CancellationToken</see> 
+        /// that will be assigned to the new continuation task.</param>
+        /// <param name="continuationOptions">The <see cref="System.Threading.Tasks.TaskContinuationOptions">
+        /// TaskContinuationOptions</see> value that controls the behavior of
+        /// the created continuation <see cref="T:System.Threading.Tasks.Task">Task</see>.</param>
+        /// <param name="scheduler">The <see cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see>
+        /// that is used to schedule the created continuation <see
+        /// cref="T:System.Threading.Tasks.Task">Task</see>.</param>
+        /// <returns>The new continuation <see cref="T:System.Threading.Tasks.Task">Task</see>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="continuationAction"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="scheduler"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array contains a null value.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is empty.</exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">The exception that is thrown when the
+        /// <paramref name="continuationOptions"/> argument specifies an invalid TaskContinuationOptions
+        /// value.</exception>
+        /// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
+        /// has already been disposed.
+        /// </exception>
+        /// <remarks>
+        /// The NotOn* and OnlyOn* <see cref="System.Threading.Tasks.TaskContinuationOptions">TaskContinuationOptions</see>, 
+        /// which constrain for which <see cref="System.Threading.Tasks.TaskStatus">TaskStatus</see> states a continuation 
+        /// will be executed, are illegal with ContinueWhenAll.
+        /// </remarks>
+        public Task ContinueWhenAll<TAntecedentResult>(Task<TAntecedentResult>[] tasks, Action<Task<TAntecedentResult>[]> continuationAction,
+            CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
+        {
+            if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction));
+
+            return TaskFactory<VoidTaskResult>.ContinueWhenAllImpl<TAntecedentResult>(tasks, null, continuationAction, continuationOptions, cancellationToken, scheduler);
+        }
+
+        /// <summary>
+        /// Creates a continuation <see cref="T:System.Threading.Tasks.Task">Task</see>
+        /// that will be started upon the completion of a set of provided Tasks.
+        /// </summary>
+        /// <typeparam name="TResult">The type of the result that is returned by the <paramref
+        /// name="continuationFunction"/>
+        /// delegate and associated with the created <see
+        /// cref="T:System.Threading.Tasks.Task{TResult}"/>.</typeparam>
+        /// <param name="tasks">The array of tasks from which to continue.</param>
+        /// <param name="continuationFunction">The function delegate to execute when all tasks in the
+        /// <paramref name="tasks"/> array have completed.</param>
+        /// <returns>The new continuation <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="continuationFunction"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array contains a null value.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is empty.</exception>
+        public Task<TResult> ContinueWhenAll<TResult>(Task[] tasks, Func<Task[], TResult> continuationFunction)
+        {
+            if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction));
+
+            return TaskFactory<TResult>.ContinueWhenAllImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler);
+        }
+
+
+        /// <summary>
+        /// Creates a continuation <see cref="T:System.Threading.Tasks.Task">Task</see>
+        /// that will be started upon the completion of a set of provided Tasks.
+        /// </summary>
+        /// <typeparam name="TResult">The type of the result that is returned by the <paramref
+        /// name="continuationFunction"/>
+        /// delegate and associated with the created <see
+        /// cref="T:System.Threading.Tasks.Task{TResult}"/>.</typeparam>
+        /// <param name="tasks">The array of tasks from which to continue.</param>
+        /// <param name="continuationFunction">The function delegate to execute when all tasks in the
+        /// <paramref name="tasks"/> array have completed.</param>
+        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken">CancellationToken</see> 
+        /// that will be assigned to the new continuation task.</param>
+        /// <returns>The new continuation <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="continuationFunction"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array contains a null value.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is empty.</exception>
+        /// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
+        /// has already been disposed.
+        /// </exception>
+        public Task<TResult> ContinueWhenAll<TResult>(Task[] tasks, Func<Task[], TResult> continuationFunction, CancellationToken cancellationToken)
+        {
+            if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction));
+
+            return TaskFactory<TResult>.ContinueWhenAllImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler);
+        }
+
+        /// <summary>
+        /// Creates a continuation <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>
+        /// that will be started upon the completion of a set of provided Tasks.
+        /// </summary>
+        /// <typeparam name="TResult">The type of the result that is returned by the <paramref
+        /// name="continuationFunction"/>
+        /// delegate and associated with the created <see
+        /// cref="T:System.Threading.Tasks.Task{TResult}"/>.</typeparam>
+        /// <param name="tasks">The array of tasks from which to continue.</param>
+        /// <param name="continuationFunction">The function delegate to execute when all tasks in the
+        /// <paramref name="tasks"/> array have completed.</param>
+        /// <param name="continuationOptions">The <see cref="System.Threading.Tasks.TaskContinuationOptions">
+        /// TaskContinuationOptions</see> value that controls the behavior of
+        /// the created continuation <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>.</param>
+        /// <returns>The new continuation <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="continuationFunction"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array contains a null value.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is empty.</exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">The exception that is thrown when the
+        /// <paramref name="continuationOptions"/> argument specifies an invalid TaskContinuationOptions
+        /// value.</exception>
+        /// <remarks>
+        /// The NotOn* and OnlyOn* <see cref="System.Threading.Tasks.TaskContinuationOptions">TaskContinuationOptions</see>, 
+        /// which constrain for which <see cref="System.Threading.Tasks.TaskStatus">TaskStatus</see> states a continuation 
+        /// will be executed, are illegal with ContinueWhenAll.
+        /// </remarks>
+        public Task<TResult> ContinueWhenAll<TResult>(Task[] tasks, Func<Task[], TResult> continuationFunction, TaskContinuationOptions continuationOptions)
+        {
+            if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction));
+
+            return TaskFactory<TResult>.ContinueWhenAllImpl(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler);
+        }
+
+        /// <summary>
+        /// Creates a continuation <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>
+        /// that will be started upon the completion of a set of provided Tasks.
+        /// </summary>
+        /// <typeparam name="TResult">The type of the result that is returned by the <paramref
+        /// name="continuationFunction"/>
+        /// delegate and associated with the created <see
+        /// cref="T:System.Threading.Tasks.Task{TResult}"/>.</typeparam>
+        /// <param name="tasks">The array of tasks from which to continue.</param>
+        /// <param name="continuationFunction">The function delegate to execute when all tasks in the
+        /// <paramref name="tasks"/> array have completed.</param>
+        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken">CancellationToken</see> 
+        /// that will be assigned to the new continuation task.</param>
+        /// <param name="continuationOptions">The <see cref="System.Threading.Tasks.TaskContinuationOptions">
+        /// TaskContinuationOptions</see> value that controls the behavior of
+        /// the created continuation <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>.</param>
+        /// <param name="scheduler">The <see cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see>
+        /// that is used to schedule the created continuation <see
+        /// cref="T:System.Threading.Tasks.Task{TResult}"/>.</param>
+        /// <returns>The new continuation <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="continuationFunction"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="scheduler"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array contains a null value.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is empty.</exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">The exception that is thrown when the
+        /// <paramref name="continuationOptions"/> argument specifies an invalid TaskContinuationOptions
+        /// value.</exception>
+        /// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
+        /// has already been disposed.
+        /// </exception>
+        /// <remarks>
+        /// The NotOn* and OnlyOn* <see cref="System.Threading.Tasks.TaskContinuationOptions">TaskContinuationOptions</see>, 
+        /// which constrain for which <see cref="System.Threading.Tasks.TaskStatus">TaskStatus</see> states a continuation 
+        /// will be executed, are illegal with ContinueWhenAll.
+        /// </remarks>
+        public Task<TResult> ContinueWhenAll<TResult>(Task[] tasks, Func<Task[], TResult> continuationFunction, CancellationToken cancellationToken,
+            TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
+        {
+            if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction));
+
+            return TaskFactory<TResult>.ContinueWhenAllImpl(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler);
+        }
+
+
+        /// <summary>
+        /// Creates a continuation <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>
+        /// that will be started upon the completion of a set of provided Tasks.
+        /// </summary>
+        /// <typeparam name="TResult">The type of the result that is returned by the <paramref
+        /// name="continuationFunction"/>
+        /// delegate and associated with the created <see
+        /// cref="T:System.Threading.Tasks.Task{TResult}"/>.</typeparam>
+        /// <typeparam name="TAntecedentResult">The type of the result of the antecedent <paramref name="tasks"/>.</typeparam>
+        /// <param name="tasks">The array of tasks from which to continue.</param>
+        /// <param name="continuationFunction">The function delegate to execute when all tasks in the
+        /// <paramref name="tasks"/> array have completed.</param>
+        /// <returns>The new continuation <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="continuationFunction"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array contains a null value.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is empty.</exception>
+        public Task<TResult> ContinueWhenAll<TAntecedentResult, TResult>(Task<TAntecedentResult>[] tasks, Func<Task<TAntecedentResult>[], TResult> continuationFunction)
+        {
+            if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction));
+
+            return TaskFactory<TResult>.ContinueWhenAllImpl<TAntecedentResult>(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler);
+        }
+
+        /// <summary>
+        /// Creates a continuation <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>
+        /// that will be started upon the completion of a set of provided Tasks.
+        /// </summary>
+        /// <typeparam name="TResult">The type of the result that is returned by the <paramref
+        /// name="continuationFunction"/>
+        /// delegate and associated with the created <see
+        /// cref="T:System.Threading.Tasks.Task{TResult}"/>.</typeparam>
+        /// <typeparam name="TAntecedentResult">The type of the result of the antecedent <paramref name="tasks"/>.</typeparam>
+        /// <param name="tasks">The array of tasks from which to continue.</param>
+        /// <param name="continuationFunction">The function delegate to execute when all tasks in the
+        /// <paramref name="tasks"/> array have completed.</param>
+        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken">CancellationToken</see> 
+        /// that will be assigned to the new continuation task.</param>
+        /// <returns>The new continuation <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="continuationFunction"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array contains a null value.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is empty.</exception>
+        /// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
+        /// has already been disposed.
+        /// </exception>
+        public Task<TResult> ContinueWhenAll<TAntecedentResult, TResult>(Task<TAntecedentResult>[] tasks, Func<Task<TAntecedentResult>[], TResult> continuationFunction,
+            CancellationToken cancellationToken)
+        {
+            if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction));
+
+            return TaskFactory<TResult>.ContinueWhenAllImpl<TAntecedentResult>(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler);
+        }
+
+        /// <summary>
+        /// Creates a continuation <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>
+        /// that will be started upon the completion of a set of provided Tasks.
+        /// </summary>
+        /// <typeparam name="TResult">The type of the result that is returned by the <paramref
+        /// name="continuationFunction"/>
+        /// delegate and associated with the created <see
+        /// cref="T:System.Threading.Tasks.Task{TResult}"/>.</typeparam>
+        /// <typeparam name="TAntecedentResult">The type of the result of the antecedent <paramref name="tasks"/>.</typeparam>
+        /// <param name="tasks">The array of tasks from which to continue.</param>
+        /// <param name="continuationFunction">The function delegate to execute when all tasks in the
+        /// <paramref name="tasks"/> array have completed.</param>
+        /// <param name="continuationOptions">The <see cref="System.Threading.Tasks.TaskContinuationOptions">
+        /// TaskContinuationOptions</see> value that controls the behavior of
+        /// the created continuation <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>.</param>
+        /// <returns>The new continuation <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="continuationFunction"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array contains a null value.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is empty.</exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">The exception that is thrown when the
+        /// <paramref name="continuationOptions"/> argument specifies an invalid TaskContinuationOptions
+        /// value.</exception>
+        /// <remarks>
+        /// The NotOn* and OnlyOn* <see cref="System.Threading.Tasks.TaskContinuationOptions">TaskContinuationOptions</see>, 
+        /// which constrain for which <see cref="System.Threading.Tasks.TaskStatus">TaskStatus</see> states a continuation 
+        /// will be executed, are illegal with ContinueWhenAll.
+        /// </remarks>
+        public Task<TResult> ContinueWhenAll<TAntecedentResult, TResult>(Task<TAntecedentResult>[] tasks, Func<Task<TAntecedentResult>[], TResult> continuationFunction,
+            TaskContinuationOptions continuationOptions)
+        {
+            if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction));
+
+            return TaskFactory<TResult>.ContinueWhenAllImpl<TAntecedentResult>(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler);
+        }
+
+        /// <summary>
+        /// Creates a continuation <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>
+        /// that will be started upon the completion of a set of provided Tasks.
+        /// </summary>
+        /// <typeparam name="TResult">The type of the result that is returned by the <paramref
+        /// name="continuationFunction"/>
+        /// delegate and associated with the created <see
+        /// cref="T:System.Threading.Tasks.Task{TResult}"/>.</typeparam>
+        /// <typeparam name="TAntecedentResult">The type of the result of the antecedent <paramref name="tasks"/>.</typeparam>
+        /// <param name="tasks">The array of tasks from which to continue.</param>
+        /// <param name="continuationFunction">The function delegate to execute when all tasks in the
+        /// <paramref name="tasks"/> array have completed.</param>
+        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken">CancellationToken</see> 
+        /// that will be assigned to the new continuation task.</param>
+        /// <param name="continuationOptions">The <see cref="System.Threading.Tasks.TaskContinuationOptions">
+        /// TaskContinuationOptions</see> value that controls the behavior of
+        /// the created continuation <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>.</param>
+        /// <param name="scheduler">The <see cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see>
+        /// that is used to schedule the created continuation <see
+        /// cref="T:System.Threading.Tasks.Task{TResult}"/>.</param>
+        /// <returns>The new continuation <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="continuationFunction"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="scheduler"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array contains a null value.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is empty.</exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">The exception that is thrown when the
+        /// <paramref name="continuationOptions"/> argument specifies an invalid TaskContinuationOptions
+        /// value.</exception>
+        /// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
+        /// has already been disposed.
+        /// </exception>
+        /// <remarks>
+        /// The NotOn* and OnlyOn* <see cref="System.Threading.Tasks.TaskContinuationOptions">TaskContinuationOptions</see>, 
+        /// which constrain for which <see cref="System.Threading.Tasks.TaskStatus">TaskStatus</see> states a continuation 
+        /// will be executed, are illegal with ContinueWhenAll.
+        /// </remarks>
+        public Task<TResult> ContinueWhenAll<TAntecedentResult, TResult>(Task<TAntecedentResult>[] tasks, Func<Task<TAntecedentResult>[], TResult> continuationFunction,
+            CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
+        {
+            if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction));
+
+            return TaskFactory<TResult>.ContinueWhenAllImpl<TAntecedentResult>(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler);
+        }
+
+        //
+        // ContinueWhenAny methods
+        //
+
+        // A Task<Task> that will be completed the first time that Invoke is called.
+        // It allows us to replace this logic:
+        //      Task<Task> promise = new Task<Task>(...);
+        //      Action<Task> completionAction = delegate(Task completingTask) { promise.TrySetResult(completingTask); }
+        //      for(int i=0; i<tasksCopy.Length; i++) tasksCopy[i].AddCompletionAction(completionAction);
+        // with this logic:
+        //      CompletionOnInvokePromise promise = new CompletionOnInvokePromise(tasksCopy);
+        //      for(int i=0; i<tasksCopy.Length; i++) tasksCopy[i].AddCompletionAction(promise);
+        // which saves a couple of allocations.
+        //
+        // Used in TaskFactory.CommonCWAnyLogic(), below.
+        internal sealed class CompleteOnInvokePromise : Task<Task>, ITaskCompletionAction
+        {
+            private IList<Task> _tasks; // must track this for cleanup
+            private int m_firstTaskAlreadyCompleted;
+
+            public CompleteOnInvokePromise(IList<Task> tasks) : base()
+            {
+                Debug.Assert(tasks != null, "Expected non-null collection of tasks");
+                _tasks = tasks;
+
+                if (DebuggerSupport.LoggingOn)
+                    DebuggerSupport.TraceOperationCreation(CausalityTraceLevel.Required, this, "TaskFactory.ContinueWhenAny", 0);
+                DebuggerSupport.AddToActiveTasks(this);
+            }
+
+            public void Invoke(Task completingTask)
+            {
+                if (m_firstTaskAlreadyCompleted == 0 &&
+                    Interlocked.Exchange(ref m_firstTaskAlreadyCompleted, 1) == 0)
+                {
+                    // This was the first Task to complete.
+
+                    bool success = TrySetResult(completingTask);
+                    Debug.Assert(success, "Only one task should have gotten to this point, and thus this must be successful.");
+
+                    // We need to remove continuations that may be left straggling on other tasks.
+                    // Otherwise, repeated calls to WhenAny using the same task could leak actions.
+                    // This may also help to avoided unnecessary invocations of this whenComplete delegate.
+                    // Note that we may be attempting to remove a continuation from a task that hasn't had it
+                    // added yet; while there's overhead there, the operation won't hurt anything.
+
+                    if (DebuggerSupport.LoggingOn)
+                    {
+                        DebuggerSupport.TraceOperationRelation(CausalityTraceLevel.Important, this, CausalityRelation.Choice);
+                        DebuggerSupport.TraceOperationCompletion(CausalityTraceLevel.Required, this, AsyncStatus.Completed);
+                    }
+                    DebuggerSupport.RemoveFromActiveTasks(this);
+
+
+                    var tasks = _tasks;
+                    int numTasks = tasks.Count;
+                    for (int i = 0; i < numTasks; i++)
+                    {
+                        var task = tasks[i];
+                        if (task != null && // if an element was erroneously nulled out concurrently, just skip it; worst case is we don't remove a continuation
+                            !task.IsCompleted)
+                            task.RemoveContinuation(this);
+                    }
+                    _tasks = null;
+                }
+            }
+
+            public bool InvokeMayRunArbitraryCode { get { return true; } }
+        }
+        // Common ContinueWhenAny logic
+        // If the tasks list is not an array, it must be an internal defensive copy so that 
+        // we don't need to be concerned about concurrent modifications to the list.  If the task list
+        // is an array, it should be a defensive copy if this functionality is being used
+        // asynchronously (e.g. WhenAny) rather than synchronously (e.g. WaitAny).
+        internal static Task<Task> CommonCWAnyLogic(IList<Task> tasks)
+        {
+            Debug.Assert(tasks != null);
+
+            // Create a promise task to be returned to the user.
+            // (If this logic ever changes, also update CommonCWAnyLogicCleanup.)
+            var promise = new CompleteOnInvokePromise(tasks);
+
+            // At the completion of any of the tasks, complete the promise.
+
+            bool checkArgsOnly = false;
+            int numTasks = tasks.Count;
+            for (int i = 0; i < numTasks; i++)
+            {
+                var task = tasks[i];
+                if (task == null) throw new ArgumentException(SR.Task_MultiTaskContinuation_NullTask, nameof(tasks));
+
+                if (checkArgsOnly) continue;
+
+                // If the promise has already completed, don't bother with checking any more tasks.
+                if (promise.IsCompleted)
+                {
+                    checkArgsOnly = true;
+                }
+                // If a task has already completed, complete the promise.
+                else if (task.IsCompleted)
+                {
+                    promise.Invoke(task);
+                    checkArgsOnly = true;
+                }
+                // Otherwise, add the completion action and keep going.
+                else
+                {
+                    task.AddCompletionAction(promise);
+                    if (promise.IsCompleted)
+                    {
+                        // One of the previous tasks that already had its continuation registered may have
+                        // raced to complete with our adding the continuation to this task.  The completion
+                        // routine would have gone through and removed the continuation from all of the tasks
+                        // with which it was already registered, but if the race causes this continuation to
+                        // be added after that, it'll never be removed.  As such, after adding the continuation,
+                        // we check to see whether the promise has already completed, and if it has, we try to
+                        // manually remove the continuation from this task.  If it was already removed, it'll be
+                        // a nop, and if we race to remove it, the synchronization in RemoveContinuation will
+                        // keep things consistent.
+                        task.RemoveContinuation(promise);
+                    }
+                }
+            }
+
+            return promise;
+        }
+
+        /// <summary>
+        /// Cleans up the operations performed by CommonCWAnyLogic in a case where
+        /// the created continuation task is being discarded.
+        /// </summary>
+        /// <param name="continuation">The task returned from CommonCWAnyLogic.</param>
+        internal static void CommonCWAnyLogicCleanup(Task<Task> continuation)
+        {
+            // Force cleanup of the promise (e.g. removing continuations from each
+            // constituent task), by completing the promise with any value.
+            ((CompleteOnInvokePromise)continuation).Invoke(null);
+        }
+
+        /// <summary>
+        /// Creates a continuation <see cref="T:System.Threading.Tasks.Task">Task</see>
+        /// that will be started upon the completion of any Task in the provided set.
+        /// </summary>
+        /// <param name="tasks">The array of tasks from which to continue when one task completes.</param>
+        /// <param name="continuationAction">The action delegate to execute when one task in the <paramref
+        /// name="tasks"/> array completes.</param>
+        /// <returns>The new continuation <see cref="T:System.Threading.Tasks.Task">Task</see>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="continuationAction"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array contains a null value.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is empty.</exception>
+        public Task ContinueWhenAny(Task[] tasks, Action<Task> continuationAction)
+        {
+            if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction));
+
+            return TaskFactory<VoidTaskResult>.ContinueWhenAnyImpl(tasks, null, continuationAction, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler);
+        }
+
+        /// <summary>
+        /// Creates a continuation <see cref="T:System.Threading.Tasks.Task">Task</see>
+        /// that will be started upon the completion of any Task in the provided set.
+        /// </summary>
+        /// <param name="tasks">The array of tasks from which to continue when one task completes.</param>
+        /// <param name="continuationAction">The action delegate to execute when one task in the <paramref
+        /// name="tasks"/> array completes.</param>
+        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken">CancellationToken</see> 
+        /// that will be assigned to the new continuation task.</param>
+        /// <returns>The new continuation <see cref="T:System.Threading.Tasks.Task">Task</see>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="continuationAction"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array contains a null value.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is empty.</exception>
+        /// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
+        /// has already been disposed.
+        /// </exception>
+        public Task ContinueWhenAny(Task[] tasks, Action<Task> continuationAction, CancellationToken cancellationToken)
+        {
+            if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction));
+
+            return TaskFactory<VoidTaskResult>.ContinueWhenAnyImpl(tasks, null, continuationAction, m_defaultContinuationOptions, cancellationToken, DefaultScheduler);
+        }
+
+        /// <summary>
+        /// Creates a continuation <see cref="T:System.Threading.Tasks.Task">Task</see>
+        /// that will be started upon the completion of any Task in the provided set.
+        /// </summary>
+        /// <param name="tasks">The array of tasks from which to continue when one task completes.</param>
+        /// <param name="continuationAction">The action delegate to execute when one task in the <paramref
+        /// name="tasks"/> array completes.</param>
+        /// <param name="continuationOptions">The <see cref="System.Threading.Tasks.TaskContinuationOptions">
+        /// TaskContinuationOptions</see> value that controls the behavior of
+        /// the created continuation <see cref="T:System.Threading.Tasks.Task">Task</see>.</param>
+        /// <returns>The new continuation <see cref="T:System.Threading.Tasks.Task">Task</see>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="continuationAction"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array contains a null value.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is empty.</exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">The exception that is thrown when the
+        /// <paramref name="continuationOptions"/> argument specifies an invalid TaskContinuationOptions
+        /// value.</exception>
+        /// <remarks>
+        /// The NotOn* and OnlyOn* <see cref="System.Threading.Tasks.TaskContinuationOptions">TaskContinuationOptions</see>, 
+        /// which constrain for which <see cref="System.Threading.Tasks.TaskStatus">TaskStatus</see> states a continuation 
+        /// will be executed, are illegal with ContinueWhenAny.
+        /// </remarks>
+        public Task ContinueWhenAny(Task[] tasks, Action<Task> continuationAction, TaskContinuationOptions continuationOptions)
+        {
+            if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction));
+
+            return TaskFactory<VoidTaskResult>.ContinueWhenAnyImpl(tasks, null, continuationAction, continuationOptions, m_defaultCancellationToken, DefaultScheduler);
+        }
+
+        /// <summary>
+        /// Creates a continuation <see cref="T:System.Threading.Tasks.Task">Task</see>
+        /// that will be started upon the completion of any Task in the provided set.
+        /// </summary>
+        /// <param name="tasks">The array of tasks from which to continue when one task completes.</param>
+        /// <param name="continuationAction">The action delegate to execute when one task in the <paramref
+        /// name="tasks"/> array completes.</param>
+        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken">CancellationToken</see> 
+        /// that will be assigned to the new continuation task.</param>
+        /// <param name="continuationOptions">The <see cref="System.Threading.Tasks.TaskContinuationOptions">
+        /// TaskContinuationOptions</see> value that controls the behavior of
+        /// the created continuation <see cref="T:System.Threading.Tasks.Task">Task</see>.</param>
+        /// <param name="scheduler">The <see cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see>
+        /// that is used to schedule the created continuation <see
+        /// cref="T:System.Threading.Tasks.Task">Task</see>.</param>
+        /// <returns>The new continuation <see cref="T:System.Threading.Tasks.Task">Task</see>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="continuationAction"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="scheduler"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array contains a null value.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is empty.</exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">The exception that is thrown when the
+        /// <paramref name="continuationOptions"/> argument specifies an invalid TaskContinuationOptions
+        /// value.</exception>
+        /// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
+        /// has already been disposed.
+        /// </exception>
+        /// <remarks>
+        /// The NotOn* and OnlyOn* <see cref="System.Threading.Tasks.TaskContinuationOptions">TaskContinuationOptions</see>, 
+        /// which constrain for which <see cref="System.Threading.Tasks.TaskStatus">TaskStatus</see> states a continuation 
+        /// will be executed, are illegal with ContinueWhenAny.
+        /// </remarks>
+        public Task ContinueWhenAny(Task[] tasks, Action<Task> continuationAction, CancellationToken cancellationToken,
+            TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
+        {
+            if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction));
+
+            return TaskFactory<VoidTaskResult>.ContinueWhenAnyImpl(tasks, null, continuationAction, continuationOptions, cancellationToken, scheduler);
+        }
+
+
+        /// <summary>
+        /// Creates a continuation <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>
+        /// that will be started upon the completion of any Task in the provided set.
+        /// </summary>
+        /// <typeparam name="TResult">The type of the result that is returned by the <paramref
+        /// name="continuationFunction"/>
+        /// delegate and associated with the created <see
+        /// cref="T:System.Threading.Tasks.Task{TResult}"/>.</typeparam>
+        /// <param name="tasks">The array of tasks from which to continue when one task completes.</param>
+        /// <param name="continuationFunction">The function delegate to execute when one task in the
+        /// <paramref name="tasks"/> array completes.</param>
+        /// <returns>The new continuation <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="continuationFunction"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array contains a null value.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is empty.</exception>
+        public Task<TResult> ContinueWhenAny<TResult>(Task[] tasks, Func<Task, TResult> continuationFunction)
+        {
+            if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction));
+
+            return TaskFactory<TResult>.ContinueWhenAnyImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler);
+        }
+
+        /// <summary>
+        /// Creates a continuation <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>
+        /// that will be started upon the completion of any Task in the provided set.
+        /// </summary>
+        /// <typeparam name="TResult">The type of the result that is returned by the <paramref
+        /// name="continuationFunction"/>
+        /// delegate and associated with the created <see
+        /// cref="T:System.Threading.Tasks.Task{TResult}"/>.</typeparam>
+        /// <param name="tasks">The array of tasks from which to continue when one task completes.</param>
+        /// <param name="continuationFunction">The function delegate to execute when one task in the
+        /// <paramref name="tasks"/> array completes.</param>
+        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken">CancellationToken</see> 
+        /// that will be assigned to the new continuation task.</param>
+        /// <returns>The new continuation <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="continuationFunction"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array contains a null value.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is empty.</exception>
+        /// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
+        /// has already been disposed.
+        /// </exception>
+        public Task<TResult> ContinueWhenAny<TResult>(Task[] tasks, Func<Task, TResult> continuationFunction, CancellationToken cancellationToken)
+        {
+            if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction));
+
+            return TaskFactory<TResult>.ContinueWhenAnyImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler);
+        }
+
+        /// <summary>
+        /// Creates a continuation <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>
+        /// that will be started upon the completion of any Task in the provided set.
+        /// </summary>
+        /// <typeparam name="TResult">The type of the result that is returned by the <paramref
+        /// name="continuationFunction"/>
+        /// delegate and associated with the created <see
+        /// cref="T:System.Threading.Tasks.Task{TResult}"/>.</typeparam>
+        /// <param name="tasks">The array of tasks from which to continue when one task completes.</param>
+        /// <param name="continuationFunction">The function delegate to execute when one task in the
+        /// <paramref name="tasks"/> array completes.</param>
+        /// <param name="continuationOptions">The <see cref="System.Threading.Tasks.TaskContinuationOptions">
+        /// TaskContinuationOptions</see> value that controls the behavior of
+        /// the created continuation <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>.</param>
+        /// <returns>The new continuation <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="continuationFunction"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array contains a null value.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is empty.</exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">The exception that is thrown when the
+        /// <paramref name="continuationOptions"/> argument specifies an invalid TaskContinuationOptions
+        /// value.</exception>
+        /// <remarks>
+        /// The NotOn* and OnlyOn* <see cref="System.Threading.Tasks.TaskContinuationOptions">TaskContinuationOptions</see>, 
+        /// which constrain for which <see cref="System.Threading.Tasks.TaskStatus">TaskStatus</see> states a continuation 
+        /// will be executed, are illegal with ContinueWhenAny.
+        /// </remarks>
+        public Task<TResult> ContinueWhenAny<TResult>(Task[] tasks, Func<Task, TResult> continuationFunction, TaskContinuationOptions continuationOptions)
+        {
+            if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction));
+
+            return TaskFactory<TResult>.ContinueWhenAnyImpl(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler);
+        }
+
+        /// <summary>
+        /// Creates a continuation <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>
+        /// that will be started upon the completion of any Task in the provided set.
+        /// </summary>
+        /// <typeparam name="TResult">The type of the result that is returned by the <paramref
+        /// name="continuationFunction"/>
+        /// delegate and associated with the created <see
+        /// cref="T:System.Threading.Tasks.Task{TResult}"/>.</typeparam>
+        /// <param name="tasks">The array of tasks from which to continue when one task completes.</param>
+        /// <param name="continuationFunction">The function delegate to execute when one task in the
+        /// <paramref name="tasks"/> array completes.</param>
+        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken">CancellationToken</see> 
+        /// that will be assigned to the new continuation task.</param>
+        /// <param name="continuationOptions">The <see cref="System.Threading.Tasks.TaskContinuationOptions">
+        /// TaskContinuationOptions</see> value that controls the behavior of
+        /// the created continuation <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>.</param>
+        /// <param name="scheduler">The <see cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see>
+        /// that is used to schedule the created continuation <see
+        /// cref="T:System.Threading.Tasks.Task{TResult}"/>.</param>
+        /// <returns>The new continuation <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="continuationFunction"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="scheduler"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array contains a null value.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is empty.</exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">The exception that is thrown when the
+        /// <paramref name="continuationOptions"/> argument specifies an invalid TaskContinuationOptions
+        /// value.</exception>
+        /// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
+        /// has already been disposed.
+        /// </exception>
+        /// <remarks>
+        /// The NotOn* and OnlyOn* <see cref="System.Threading.Tasks.TaskContinuationOptions">TaskContinuationOptions</see>, 
+        /// which constrain for which <see cref="System.Threading.Tasks.TaskStatus">TaskStatus</see> states a continuation 
+        /// will be executed, are illegal with ContinueWhenAny.
+        /// </remarks>
+        public Task<TResult> ContinueWhenAny<TResult>(Task[] tasks, Func<Task, TResult> continuationFunction, CancellationToken cancellationToken,
+            TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
+        {
+            if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction));
+
+            return TaskFactory<TResult>.ContinueWhenAnyImpl(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler);
+        }
+
+        /// <summary>
+        /// Creates a continuation <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>
+        /// that will be started upon the completion of any Task in the provided set.
+        /// </summary>
+        /// <typeparam name="TResult">The type of the result that is returned by the <paramref
+        /// name="continuationFunction"/>
+        /// delegate and associated with the created <see
+        /// cref="T:System.Threading.Tasks.Task{TResult}"/>.</typeparam>
+        /// <typeparam name="TAntecedentResult">The type of the result of the antecedent <paramref name="tasks"/>.</typeparam>
+        /// <param name="tasks">The array of tasks from which to continue when one task completes.</param>
+        /// <param name="continuationFunction">The function delegate to execute when one task in the
+        /// <paramref name="tasks"/> array completes.</param>
+        /// <returns>The new continuation <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="continuationFunction"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array contains a null value.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is empty.</exception>
+        public Task<TResult> ContinueWhenAny<TAntecedentResult, TResult>(Task<TAntecedentResult>[] tasks, Func<Task<TAntecedentResult>, TResult> continuationFunction)
+        {
+            if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction));
+            return TaskFactory<TResult>.ContinueWhenAnyImpl<TAntecedentResult>(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler);
+        }
+
+        /// <summary>
+        /// Creates a continuation <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>
+        /// that will be started upon the completion of any Task in the provided set.
+        /// </summary>
+        /// <typeparam name="TResult">The type of the result that is returned by the <paramref
+        /// name="continuationFunction"/>
+        /// delegate and associated with the created <see
+        /// cref="T:System.Threading.Tasks.Task{TResult}"/>.</typeparam>
+        /// <typeparam name="TAntecedentResult">The type of the result of the antecedent <paramref name="tasks"/>.</typeparam>
+        /// <param name="tasks">The array of tasks from which to continue when one task completes.</param>
+        /// <param name="continuationFunction">The function delegate to execute when one task in the
+        /// <paramref name="tasks"/> array completes.</param>
+        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken">CancellationToken</see> 
+        /// that will be assigned to the new continuation task.</param>
+        /// <returns>The new continuation <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="continuationFunction"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array contains a null value.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is empty.</exception>
+        /// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
+        /// has already been disposed.
+        /// </exception>
+        public Task<TResult> ContinueWhenAny<TAntecedentResult, TResult>(Task<TAntecedentResult>[] tasks, Func<Task<TAntecedentResult>, TResult> continuationFunction,
+            CancellationToken cancellationToken)
+        {
+            if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction));
+
+            return TaskFactory<TResult>.ContinueWhenAnyImpl<TAntecedentResult>(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler);
+        }
+
+        /// <summary>
+        /// Creates a continuation <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>
+        /// that will be started upon the completion of any Task in the provided set.
+        /// </summary>
+        /// <typeparam name="TResult">The type of the result that is returned by the <paramref
+        /// name="continuationFunction"/>
+        /// delegate and associated with the created <see
+        /// cref="T:System.Threading.Tasks.Task{TResult}"/>.</typeparam>
+        /// <typeparam name="TAntecedentResult">The type of the result of the antecedent <paramref name="tasks"/>.</typeparam>
+        /// <param name="tasks">The array of tasks from which to continue when one task completes.</param>
+        /// <param name="continuationFunction">The function delegate to execute when one task in the
+        /// <paramref name="tasks"/> array completes.</param>
+        /// <param name="continuationOptions">The <see cref="System.Threading.Tasks.TaskContinuationOptions">
+        /// TaskContinuationOptions</see> value that controls the behavior of
+        /// the created continuation <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>.</param>
+        /// <returns>The new continuation <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="continuationFunction"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array contains a null value.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is empty.</exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">The exception that is thrown when the
+        /// <paramref name="continuationOptions"/> argument specifies an invalid TaskContinuationOptions
+        /// value.</exception>
+        /// <remarks>
+        /// The NotOn* and OnlyOn* <see cref="System.Threading.Tasks.TaskContinuationOptions">TaskContinuationOptions</see>, 
+        /// which constrain for which <see cref="System.Threading.Tasks.TaskStatus">TaskStatus</see> states a continuation 
+        /// will be executed, are illegal with ContinueWhenAny.
+        /// </remarks>
+        public Task<TResult> ContinueWhenAny<TAntecedentResult, TResult>(Task<TAntecedentResult>[] tasks, Func<Task<TAntecedentResult>, TResult> continuationFunction,
+            TaskContinuationOptions continuationOptions)
+        {
+            if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction));
+
+            return TaskFactory<TResult>.ContinueWhenAnyImpl<TAntecedentResult>(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler);
+        }
+
+        /// <summary>
+        /// Creates a continuation <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>
+        /// that will be started upon the completion of any Task in the provided set.
+        /// </summary>
+        /// <typeparam name="TResult">The type of the result that is returned by the <paramref
+        /// name="continuationFunction"/>
+        /// delegate and associated with the created <see
+        /// cref="T:System.Threading.Tasks.Task{TResult}"/>.</typeparam>
+        /// <typeparam name="TAntecedentResult">The type of the result of the antecedent <paramref name="tasks"/>.</typeparam>
+        /// <param name="tasks">The array of tasks from which to continue when one task completes.</param>
+        /// <param name="continuationFunction">The function delegate to execute when one task in the
+        /// <paramref name="tasks"/> array completes.</param>
+        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken">CancellationToken</see> 
+        /// that will be assigned to the new continuation task.</param>
+        /// <param name="continuationOptions">The <see cref="System.Threading.Tasks.TaskContinuationOptions">
+        /// TaskContinuationOptions</see> value that controls the behavior of
+        /// the created continuation <see cref="T:System.Threading.Tasks.Task{TResult}">Task</see>.</param>
+        /// <param name="scheduler">The <see cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see>
+        /// that is used to schedule the created continuation <see
+        /// cref="T:System.Threading.Tasks.Task{TResult}"/>.</param>
+        /// <returns>The new continuation <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="continuationFunction"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="scheduler"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array contains a null value.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is empty.</exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">The exception that is thrown when the
+        /// <paramref name="continuationOptions"/> argument specifies an invalid TaskContinuationOptions
+        /// value.</exception>
+        /// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
+        /// has already been disposed.
+        /// </exception>
+        /// <remarks>
+        /// The NotOn* and OnlyOn* <see cref="System.Threading.Tasks.TaskContinuationOptions">TaskContinuationOptions</see>, 
+        /// which constrain for which <see cref="System.Threading.Tasks.TaskStatus">TaskStatus</see> states a continuation 
+        /// will be executed, are illegal with ContinueWhenAny.
+        /// </remarks>
+        public Task<TResult> ContinueWhenAny<TAntecedentResult, TResult>(Task<TAntecedentResult>[] tasks, Func<Task<TAntecedentResult>, TResult> continuationFunction,
+            CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
+        {
+            if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction));
+
+            return TaskFactory<TResult>.ContinueWhenAnyImpl<TAntecedentResult>(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler);
+        }
+
+
+        /// <summary>
+        /// Creates a continuation <see cref="T:System.Threading.Tasks.Task">Task</see>
+        /// that will be started upon the completion of any Task in the provided set.
+        /// </summary>
+        /// <typeparam name="TAntecedentResult">The type of the result of the antecedent <paramref name="tasks"/>.</typeparam>
+        /// <param name="tasks">The array of tasks from which to continue when one task completes.</param>
+        /// <param name="continuationAction">The action delegate to execute when one task in the
+        /// <paramref name="tasks"/> array completes.</param>
+        /// <returns>The new continuation <see cref="T:System.Threading.Tasks.Task"/>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="continuationAction"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array contains a null value.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is empty.</exception>
+        public Task ContinueWhenAny<TAntecedentResult>(Task<TAntecedentResult>[] tasks, Action<Task<TAntecedentResult>> continuationAction)
+        {
+            if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction));
+
+            return TaskFactory<VoidTaskResult>.ContinueWhenAnyImpl<TAntecedentResult>(tasks, null, continuationAction, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler);
+        }
+
+        /// <summary>
+        /// Creates a continuation <see cref="T:System.Threading.Tasks.Task">Task</see>
+        /// that will be started upon the completion of any Task in the provided set.
+        /// </summary>
+        /// <typeparam name="TAntecedentResult">The type of the result of the antecedent <paramref name="tasks"/>.</typeparam>
+        /// <param name="tasks">The array of tasks from which to continue when one task completes.</param>
+        /// <param name="continuationAction">The action delegate to execute when one task in the
+        /// <paramref name="tasks"/> array completes.</param>
+        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken">CancellationToken</see> 
+        /// that will be assigned to the new continuation task.</param>
+        /// <returns>The new continuation <see cref="T:System.Threading.Tasks.Task"/>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="continuationAction"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array contains a null value.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is empty.</exception>
+        /// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
+        /// has already been disposed.
+        /// </exception>
+        public Task ContinueWhenAny<TAntecedentResult>(Task<TAntecedentResult>[] tasks, Action<Task<TAntecedentResult>> continuationAction,
+            CancellationToken cancellationToken)
+        {
+            if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction));
+
+            return TaskFactory<VoidTaskResult>.ContinueWhenAnyImpl<TAntecedentResult>(tasks, null, continuationAction, m_defaultContinuationOptions, cancellationToken, DefaultScheduler);
+        }
+
+        /// <summary>
+        /// Creates a continuation <see cref="T:System.Threading.Tasks.Task">Task</see>
+        /// that will be started upon the completion of any Task in the provided set.
+        /// </summary>
+        /// <typeparam name="TAntecedentResult">The type of the result of the antecedent <paramref name="tasks"/>.</typeparam>
+        /// <param name="tasks">The array of tasks from which to continue when one task completes.</param>
+        /// <param name="continuationAction">The action delegate to execute when one task in the
+        /// <paramref name="tasks"/> array completes.</param>
+        /// <param name="continuationOptions">The <see cref="System.Threading.Tasks.TaskContinuationOptions">
+        /// TaskContinuationOptions</see> value that controls the behavior of
+        /// the created continuation <see cref="T:System.Threading.Tasks.Task">Task</see>.</param>
+        /// <returns>The new continuation <see cref="T:System.Threading.Tasks.Task"/>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="continuationAction"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array contains a null value.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is empty.</exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">The exception that is thrown when the
+        /// <paramref name="continuationOptions"/> argument specifies an invalid TaskContinuationOptions
+        /// value.</exception>
+        /// <remarks>
+        /// The NotOn* and OnlyOn* <see cref="System.Threading.Tasks.TaskContinuationOptions">TaskContinuationOptions</see>, 
+        /// which constrain for which <see cref="System.Threading.Tasks.TaskStatus">TaskStatus</see> states a continuation 
+        /// will be executed, are illegal with ContinueWhenAny.
+        /// </remarks>
+        public Task ContinueWhenAny<TAntecedentResult>(Task<TAntecedentResult>[] tasks, Action<Task<TAntecedentResult>> continuationAction,
+            TaskContinuationOptions continuationOptions)
+        {
+            if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction));
+
+            return TaskFactory<VoidTaskResult>.ContinueWhenAnyImpl<TAntecedentResult>(tasks, null, continuationAction, continuationOptions, m_defaultCancellationToken, DefaultScheduler);
+        }
+
+        /// <summary>
+        /// Creates a continuation <see cref="T:System.Threading.Tasks.Task">Task</see>
+        /// that will be started upon the completion of any Task in the provided set.
+        /// </summary>
+        /// <typeparam name="TAntecedentResult">The type of the result of the antecedent <paramref name="tasks"/>.</typeparam>
+        /// <param name="tasks">The array of tasks from which to continue when one task completes.</param>
+        /// <param name="continuationAction">The action delegate to execute when one task in the
+        /// <paramref name="tasks"/> array completes.</param>
+        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken">CancellationToken</see> 
+        /// that will be assigned to the new continuation task.</param>
+        /// <param name="continuationOptions">The <see cref="System.Threading.Tasks.TaskContinuationOptions">
+        /// TaskContinuationOptions</see> value that controls the behavior of
+        /// the created continuation <see cref="T:System.Threading.Tasks.Task">Task</see>.</param>
+        /// <param name="scheduler">The <see cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see>
+        /// that is used to schedule the created continuation <see
+        /// cref="T:System.Threading.Tasks.Task{TResult}"/>.</param>
+        /// <returns>The new continuation <see cref="T:System.Threading.Tasks.Task"/>.</returns>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="continuationAction"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentNullException">The exception that is thrown when the
+        /// <paramref name="scheduler"/> argument is null.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array contains a null value.</exception>
+        /// <exception cref="T:System.ArgumentException">The exception that is thrown when the
+        /// <paramref name="tasks"/> array is empty.</exception>
+        /// <exception cref="T:System.ArgumentOutOfRangeException">The exception that is thrown when the
+        /// <paramref name="continuationOptions"/> argument specifies an invalid TaskContinuationOptions
+        /// value.</exception>
+        /// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
+        /// has already been disposed.
+        /// </exception>
+        /// <remarks>
+        /// The NotOn* and OnlyOn* <see cref="System.Threading.Tasks.TaskContinuationOptions">TaskContinuationOptions</see>, 
+        /// which constrain for which <see cref="System.Threading.Tasks.TaskStatus">TaskStatus</see> states a continuation 
+        /// will be executed, are illegal with ContinueWhenAny.
+        /// </remarks>
+        public Task ContinueWhenAny<TAntecedentResult>(Task<TAntecedentResult>[] tasks, Action<Task<TAntecedentResult>> continuationAction,
+            CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
+        {
+            if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction));
+
+            return TaskFactory<VoidTaskResult>.ContinueWhenAnyImpl<TAntecedentResult>(tasks, null, continuationAction, continuationOptions, cancellationToken, scheduler);
+        }
+
+        // Check task array and return a defensive copy.
+        // Used with ContinueWhenAll()/ContinueWhenAny().
+        internal static Task[] CheckMultiContinuationTasksAndCopy(Task[] tasks)
+        {
+            if (tasks == null)
+                throw new ArgumentNullException(nameof(tasks));
+            if (tasks.Length == 0)
+                throw new ArgumentException(SR.Task_MultiTaskContinuation_EmptyTaskList, nameof(tasks));
+
+            Task[] tasksCopy = new Task[tasks.Length];
+            for (int i = 0; i < tasks.Length; i++)
+            {
+                tasksCopy[i] = tasks[i];
+
+                if (tasksCopy[i] == null)
+                    throw new ArgumentException(SR.Task_MultiTaskContinuation_NullTask, nameof(tasks));
+            }
+
+            return tasksCopy;
+        }
+
+        internal static Task<TResult>[] CheckMultiContinuationTasksAndCopy<TResult>(Task<TResult>[] tasks)
+        {
+            if (tasks == null)
+                throw new ArgumentNullException(nameof(tasks));
+            if (tasks.Length == 0)
+                throw new ArgumentException(SR.Task_MultiTaskContinuation_EmptyTaskList, nameof(tasks));
+
+            Task<TResult>[] tasksCopy = new Task<TResult>[tasks.Length];
+            for (int i = 0; i < tasks.Length; i++)
+            {
+                tasksCopy[i] = tasks[i];
+
+                if (tasksCopy[i] == null)
+                    throw new ArgumentException(SR.Task_MultiTaskContinuation_NullTask, nameof(tasks));
+            }
+
+            return tasksCopy;
+        }
+
+        // Throw an exception if "options" argument specifies illegal options
+        internal static void CheckMultiTaskContinuationOptions(TaskContinuationOptions continuationOptions)
+        {
+            // Construct a mask to check for illegal options
+            const TaskContinuationOptions NotOnAny = TaskContinuationOptions.NotOnCanceled |
+                                               TaskContinuationOptions.NotOnFaulted |
+                                               TaskContinuationOptions.NotOnRanToCompletion;
+
+            // Check that LongRunning and ExecuteSynchronously are not specified together
+            const TaskContinuationOptions illegalMask = TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.LongRunning;
+            if ((continuationOptions & illegalMask) == illegalMask)
+            {
+                throw new ArgumentOutOfRangeException(nameof(continuationOptions), SR.Task_ContinueWith_ESandLR);
+            }
+
+            // Check that no nonsensical options are specified.
+            if ((continuationOptions & ~(
+                TaskContinuationOptions.LongRunning |
+                TaskContinuationOptions.PreferFairness |
+                TaskContinuationOptions.AttachedToParent |
+                TaskContinuationOptions.DenyChildAttach |
+                TaskContinuationOptions.HideScheduler |
+                TaskContinuationOptions.LazyCancellation |
+                NotOnAny |
+                TaskContinuationOptions.ExecuteSynchronously)) != 0)
+            {
+                throw new ArgumentOutOfRangeException(nameof(continuationOptions));
+            }
+
+            // Check that no "fire" options are specified.
+            if ((continuationOptions & NotOnAny) != 0)
+                throw new ArgumentOutOfRangeException(nameof(continuationOptions), SR.Task_MultiTaskContinuation_FireOptions);
+        }
+    }
+}

+ 71 - 0
mcs/class/System.Private.CoreLib/temp/TaskTrace.cs

@@ -0,0 +1,71 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+namespace Internal.Threading.Tasks.Tracing
+{
+    /// <summary>
+    /// Helper class for reporting <see cref="System.Threading.Tasks.Task"/>-related events.
+    /// Calls are forwarded to an instance of <see cref="TaskTraceCallbacks"/>, if one has been
+    /// provided.
+    /// </summary>
+    public static class TaskTrace
+    {
+        public static bool Enabled
+        {
+            get
+            {
+                    return false;
+            }
+        }
+
+//        public static void Initialize(TaskTraceCallbacks callbacks)
+//        {
+//        }
+
+        public static void TaskWaitBegin_Asynchronous(
+            int OriginatingTaskSchedulerID,
+            int OriginatingTaskID,
+            int TaskID)
+        {
+        }
+
+        public static void TaskWaitBegin_Synchronous(
+            int OriginatingTaskSchedulerID,
+            int OriginatingTaskID,
+            int TaskID)
+        {
+        }
+
+        public static void TaskWaitEnd(
+            int OriginatingTaskSchedulerID,
+            int OriginatingTaskID,
+            int TaskID)
+        {
+        }
+
+        public static void TaskScheduled(
+            int OriginatingTaskSchedulerID,
+            int OriginatingTaskID,
+            int TaskID,
+            int CreatingTaskID,
+            int TaskCreationOptions)
+        {
+        }
+
+        public static void TaskStarted(
+            int OriginatingTaskSchedulerID,
+            int OriginatingTaskID,
+            int TaskID)
+        {
+        }
+
+        public static void TaskCompleted(
+            int OriginatingTaskSchedulerID,
+            int OriginatingTaskID,
+            int TaskID,
+            bool IsExceptional)
+        {
+        }
+    }
+}

+ 10 - 9
mcs/class/corlib/ReferenceSources/Buffer.cs

@@ -7,6 +7,10 @@ using nuint = System.UInt32;
 using System.Runtime.CompilerServices;
 using System.Runtime;
 
+#if NETCORE
+using Internal.Runtime.CompilerServices;
+#endif
+
 namespace System
 {
 	partial class Buffer
@@ -24,7 +28,7 @@ namespace System
 
 			int length = _ByteLength (array);
 			if (length < 0)
-				throw new ArgumentException (Locale.GetText ("Object must be an array of primitives."));
+				throw new ArgumentException ("Object must be an array of primitives.");
 
 			return length;
 		}
@@ -54,25 +58,22 @@ namespace System
 				throw new ArgumentNullException ("dst");
 
 			if (srcOffset < 0)
-				throw new ArgumentOutOfRangeException ("srcOffset", Locale.GetText(
-					"Non-negative number required."));
+				throw new ArgumentOutOfRangeException ("srcOffset", "Non-negative number required.");
 
 			if (dstOffset < 0)
-				throw new ArgumentOutOfRangeException ("dstOffset", Locale.GetText (
-					"Non-negative number required."));
+				throw new ArgumentOutOfRangeException ("dstOffset", "Non-negative number required.");
 
 			if (count < 0)
-				throw new ArgumentOutOfRangeException ("count", Locale.GetText (
-					"Non-negative number required."));
+				throw new ArgumentOutOfRangeException ("count", "Non-negative number required.");
 
 			// We do the checks in unmanaged code for performance reasons
 			bool res = InternalBlockCopy (src, srcOffset, dst, dstOffset, count);
 			if (!res) {
 				// watch for integer overflow
 				if ((srcOffset > ByteLength (src) - count) || (dstOffset > ByteLength (dst) - count))
-					throw new ArgumentException (Locale.GetText (
+					throw new ArgumentException (
 						"Offset and length were out of bounds for the array or count is greater than " + 
-						"the number of elements from index to the end of the source collection."));
+						"the number of elements from index to the end of the source collection.");
 			}
 		}
 

+ 0 - 1
mcs/class/corlib/ReferenceSources/JitHelpers.cs

@@ -1,7 +1,6 @@
 
 namespace System.Runtime.CompilerServices {
 
-	[FriendAccessAllowed]
 	internal static class JitHelpers
 	{
 		static internal T UnsafeCast<T>(Object o) where T : class

+ 4 - 0
mcs/class/corlib/ReferenceSources/String.cs

@@ -48,6 +48,10 @@ using System.Collections.Generic;
 using System.Runtime.InteropServices;
 using System.Diagnostics;
 
+#if NETCORE
+using Internal.Runtime.CompilerServices;
+#endif
+
 namespace System
 {
 	partial class String

+ 2 - 0
mcs/class/corlib/ReferenceSources/Type.cs

@@ -176,11 +176,13 @@ namespace System
 			return !object.ReferenceEquals (left, right);
 		}
 
+#if !NETCORE
         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
         public static Type ReflectionOnlyGetType (String typeName, bool throwIfNotFound, bool ignoreCase) 
         {
             StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
             return RuntimeType.GetType (typeName, throwIfNotFound, ignoreCase, true /*reflectionOnly*/, ref stackMark);
         }
+#endif
 	}
 }

+ 9 - 9
mcs/class/corlib/System.Diagnostics.Tracing/EventSource.cs

@@ -277,56 +277,56 @@ namespace System.Diagnostics.Tracing
 		{
 		}
 
-		[MonoTODO]
+//		[MonoTODO]
 		public event EventHandler<EventCommandEventArgs> EventCommandExecuted
 		{
 			add { throw new NotImplementedException (); }
 			remove { throw new NotImplementedException (); }
 		}
 
-		[MonoTODO]
+//		[MonoTODO]
 		public static string GenerateManifest (Type eventSourceType, string assemblyPathToIncludeInManifest)
 		{
 			throw new NotImplementedException ();
 		}
 
-		[MonoTODO]
+//		[MonoTODO]
 		public static string GenerateManifest (Type eventSourceType, string assemblyPathToIncludeInManifest, EventManifestOptions flags)
 		{
 			throw new NotImplementedException ();
 		}
 
-		[MonoTODO]
+//		[MonoTODO]
 		public static Guid GetGuid (Type eventSourceType)
 		{
 			throw new NotImplementedException ();
 		}
 
-		[MonoTODO]
+//		[MonoTODO]
 		public static string GetName (Type eventSourceType)
 		{
 			throw new NotImplementedException ();
 		}
 
-		[MonoTODO]
+//		[MonoTODO]
 		public static IEnumerable<EventSource> GetSources ()
 		{
 			throw new NotImplementedException ();
 		}
 
-		[MonoTODO]
+//		[MonoTODO]
 		public static void SendCommand (EventSource eventSource, EventCommand command, IDictionary<string, string> commandArguments)
 		{
 			throw new NotImplementedException ();
 		}
 
-		[MonoTODO]
+//		[MonoTODO]
 		public static void SetCurrentThreadActivityId (Guid activityId)
 		{
 			throw new NotImplementedException ();
 		}
 
-		[MonoTODO]
+//		[MonoTODO]
 		public static void SetCurrentThreadActivityId (Guid activityId, out Guid oldActivityThatWillContinue)
 		{
 			throw new NotImplementedException ();

+ 4 - 1
mcs/class/corlib/System.Diagnostics/StackTrace.cs

@@ -35,7 +35,6 @@ using System.Reflection;
 using System.Runtime.CompilerServices;
 using System.Runtime.InteropServices;
 using System.Security;
-using System.Security.Permissions;
 using System.Text;
 using System.Threading;
 using System.IO;
@@ -44,7 +43,9 @@ namespace System.Diagnostics {
 
 	[Serializable]
 	[ComVisible (true)]
+#if !NETCORE
 	[MonoTODO ("Serialized objects are not compatible with .NET")]
+#endif
 	public class StackTrace {
 
         // TraceFormat is Used to specify options for how the 
@@ -147,7 +148,9 @@ namespace System.Diagnostics {
 			this.frames [0] = frame;
 		}
 
+#if !NETCORE
 		[MonoLimitation ("Not possible to create StackTraces from other threads")]
+#endif
 		[Obsolete]
 		public StackTrace (Thread targetThread, bool needFileInfo)
 		{

+ 5 - 5
mcs/class/corlib/System.Globalization/CultureInfo.cs

@@ -34,14 +34,13 @@ using System.Collections.Generic;
 using System.Threading;
 using System.Runtime.CompilerServices;
 using System.Runtime.InteropServices;
-using System.Diagnostics.Contracts;
 
 namespace System.Globalization
 {
 	[System.Runtime.InteropServices.ComVisible (true)]
 	[Serializable]
 	[StructLayout (LayoutKind.Sequential)]
-	public class CultureInfo : ICloneable, IFormatProvider
+	public partial class CultureInfo : ICloneable, IFormatProvider
 	{
 		static volatile CultureInfo invariant_culture_info = new CultureInfo (InvariantCultureId, false, true);
 		static object shared_table_lock = new object ();
@@ -311,7 +310,9 @@ namespace System.Globalization
 			}
 		}
 
+#if !NETCORE
 		[MonoLimitation ("Optional calendars are not supported only default calendar is returned")]
+#endif
 		public virtual Calendar[] OptionalCalendars {
 			get {
 				return new[] { Calendar };
@@ -780,7 +781,9 @@ namespace System.Globalization
 			}
 		}
 
+#if !NETCORE
 		[MonoTODO ("Currently it ignores the altName parameter")]
+#endif
 		public static CultureInfo GetCultureInfo (string name, string altName) {
 			if (name == null)
 				throw new ArgumentNullException ("null");
@@ -1134,7 +1137,6 @@ namespace System.Globalization
                                 obj.GetType(),
                                 container.GetType()));
             }
-            Contract.EndContractBlock();
         }
 
         // For resource lookup, we consider a culture the invariant culture by name equality.
@@ -1167,8 +1169,6 @@ namespace System.Globalization
         }
 
         internal static bool VerifyCultureName(CultureInfo culture, bool throwException) {
-            Contract.Assert(culture!=null, "[CultureInfo.VerifyCultureName]culture!=null");
-
             //If we have an instance of one of our CultureInfos, the user can't have changed the
             //name and we know that all names are valid in files.
             if (!culture.m_isInherited) {

+ 16 - 11
mcs/class/corlib/System.Reflection/AssemblyName.cs

@@ -34,15 +34,15 @@ using System.Globalization;
 using System.Runtime.Serialization;
 using System.Security;
 using System.Security.Cryptography;
-using System.Security.Permissions;
 using System.Text;
 using System.Runtime.InteropServices;
 using System.Runtime.CompilerServices;
 using System.IO;
 
 using Mono;
-using Mono.Security;
+#if !MOBILE && !NETCORE
 using Mono.Security.Cryptography;
+#endif
 
 namespace System.Reflection {
 
@@ -51,12 +51,14 @@ namespace System.Reflection {
 //	http://www.ietf.org/rfc/rfc2396.txt
 
 	[ComVisible (true)]
+#if !NETCORE
 	[ComDefaultInterfaceAttribute (typeof (_AssemblyName))]
-	[Serializable]
 	[ClassInterfaceAttribute (ClassInterfaceType.None)]
+#endif
+	[Serializable]	
 	[StructLayout (LayoutKind.Sequential)]
-#if MOBILE
-	public sealed class AssemblyName  : ICloneable, ISerializable, IDeserializationCallback {
+#if MOBILE || NETCORE
+	public sealed partial class AssemblyName  : ICloneable, ISerializable, IDeserializationCallback {
 #else
 	public sealed class AssemblyName  : ICloneable, ISerializable, IDeserializationCallback, _AssemblyName {
 #endif
@@ -110,7 +112,6 @@ namespace System.Reflection {
 			}
 		}
 		
-		[MonoLimitation ("Not used, as the values are too limited;  Mono supports more")]
 		public ProcessorArchitecture ProcessorArchitecture {
 			get {
 				return processor_architecture;
@@ -149,7 +150,12 @@ namespace System.Reflection {
 			get {
 				if (codebase == null)
 					return null;
-				return Uri.EscapeString (codebase, false, true, true);
+
+#if NETCORE
+				throw new NotImplementedException ();
+#else
+				return Mono.Security.Uri.EscapeString (codebase, false, true, true);
+#endif
 			}
 		}
 
@@ -277,7 +283,7 @@ namespace System.Reflection {
 				switch (publicKey [0]) {
 				case 0x00: // public key inside a header
 					if (publicKey.Length > 12 && publicKey [12] == 0x06) {
-#if MOBILE
+#if MOBILE || NETCORE
 						return true;
 #else
 						try {
@@ -290,7 +296,7 @@ namespace System.Reflection {
 					}
 					break;
 				case 0x06: // public key
-#if MOBILE
+#if MOBILE || NETCORE
 					return true;
 #else
 					try {
@@ -363,7 +369,6 @@ namespace System.Reflection {
 			keyToken = publicKeyToken;
 		}
 
-		[SecurityPermission (SecurityAction.Demand, SerializationFormatter = true)]
 		public void GetObjectData (SerializationInfo info, StreamingContext context)
 		{
 			if (info == null)
@@ -428,7 +433,7 @@ namespace System.Reflection {
 			return aname;
 		}
 
-#if !MOBILE
+#if !MOBILE && !NETCORE
 		void _AssemblyName.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
 		{
 			throw new NotImplementedException ();

+ 2 - 2
mcs/class/corlib/System.Reflection/CustomAttributeData.cs

@@ -89,9 +89,9 @@ namespace System.Reflection {
 			ResolveArgumentsInternal (ctorInfo, lazyData.assembly, lazyData.data, lazyData.data_length, out ctor_args, out named_args);
 
 			this.ctorArgs = Array.AsReadOnly<CustomAttributeTypedArgument>
-				(ctor_args != null ? UnboxValues<CustomAttributeTypedArgument> (ctor_args) : EmptyArray<CustomAttributeTypedArgument>.Value);
+				(ctor_args != null ? UnboxValues<CustomAttributeTypedArgument> (ctor_args) : Array.Empty<CustomAttributeTypedArgument>());
 			this.namedArgs = Array.AsReadOnly<CustomAttributeNamedArgument> 
-				(named_args != null ? UnboxValues<CustomAttributeNamedArgument> (named_args) : EmptyArray<CustomAttributeNamedArgument>.Value);
+				(named_args != null ? UnboxValues<CustomAttributeNamedArgument> (named_args) : Array.Empty<CustomAttributeNamedArgument>());
 			
 			lazyData = null;
 		}

+ 0 - 3
mcs/class/corlib/System.Reflection/MonoMethod.cs

@@ -42,7 +42,6 @@ using System.Security;
 using System.Threading;
 using System.Text;
 using System.Diagnostics;
-using System.Diagnostics.Contracts;
 
 namespace System.Reflection {
 	
@@ -175,7 +174,6 @@ namespace System.Reflection {
         {
             if (info == null)
                 throw new ArgumentNullException("info");
-            Contract.EndContractBlock();
 
             MemberInfoSerializationHolder.GetSerializationInfo(
                 info,
@@ -695,7 +693,6 @@ namespace System.Reflection {
         {
             if (info == null)
                 throw new ArgumentNullException("info");
-            Contract.EndContractBlock();
             MemberInfoSerializationHolder.GetSerializationInfo(
                 info,
                 Name,

+ 2 - 0
mcs/class/corlib/System.Runtime.CompilerServices/ConditionalWeakTable.cs

@@ -334,8 +334,10 @@ namespace System.Runtime.CompilerServices
 		// if you know for sure that either you won't run into dead locks or you need to live with the
 		// possiblity
 		//--------------------------------------------------------------------------------------------
+#if !MONO
 		[System.Security.SecuritySafeCritical]
 		[FriendAccessAllowed]
+#endif
 		internal TKey FindEquivalentKeyUnsafe(TKey key, out TValue value)
 		{
 			lock (_lock)

+ 11 - 10
mcs/class/corlib/System.Runtime.CompilerServices/RuntimeHelpers.cs

@@ -35,7 +35,7 @@ using System.Reflection;
 
 namespace System.Runtime.CompilerServices
 {
-	public static class RuntimeHelpers
+	public static partial class RuntimeHelpers
 	{
 		public delegate void TryCode (Object userData);
 
@@ -106,24 +106,24 @@ namespace System.Runtime.CompilerServices
 			return SufficientExecutionStack ();
 		}
 
-		[MonoTODO("Currently a no-op")]
+//		[MonoTODO("Currently a no-op")]
 		public static void ExecuteCodeWithGuaranteedCleanup (TryCode code, CleanupCode backoutCode, Object userData)
 		{
 		}
 
-		[MonoTODO("Currently a no-op")]
+//		[MonoTODO("Currently a no-op")]
 		[ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
 		public static void PrepareConstrainedRegions ()
 		{
 		}
 
-		[MonoTODO("Currently a no-op")]
+//		[MonoTODO("Currently a no-op")]
 		[ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
 		public static void PrepareConstrainedRegionsNoOP ()
 		{
 		}
 
-		[MonoTODO("Currently a no-op")]
+//		[MonoTODO("Currently a no-op")]
 		[ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
 		public static void ProbeForSufficientStack()
 		{
@@ -139,7 +139,7 @@ namespace System.Runtime.CompilerServices
 		// then adds that combination to e.g. AppDomain.DomainUnload, then the client is responsible
 		// for his own preparation.
 		[System.Security.SecurityCritical]  // auto-generated_required
-		[MonoTODO("Currently a no-op")]
+//		[MonoTODO("Currently a no-op")]
 		public static void PrepareDelegate (Delegate d)
 		{
 		}
@@ -157,18 +157,17 @@ namespace System.Runtime.CompilerServices
 		// NOTE: that for the NGen case you can sidestep the required ReliabilityContract
 		// by using the [PrePrepareMethod] attribute.
 		[System.Security.SecurityCritical]  // auto-generated_required
-		[ResourceExposure(ResourceScope.None)]
-		[MonoTODO("Currently a no-op")]
+//		[MonoTODO("Currently a no-op")]
 		public static void PrepareContractedDelegate(Delegate d)
 		{
 		}
 
-		[MonoTODO("Currently a no-op")]
+//		[MonoTODO("Currently a no-op")]
 		public static void PrepareMethod (RuntimeMethodHandle method)
 		{
 		}
 
-		[MonoTODO("Currently a no-op")]
+//		[MonoTODO("Currently a no-op")]
 		public static void PrepareMethod (RuntimeMethodHandle method, RuntimeTypeHandle[] instantiation)
 		{
 		}
@@ -190,9 +189,11 @@ namespace System.Runtime.CompilerServices
 			return !typeof (T).IsValueType || RuntimeTypeHandle.HasReferences ((typeof (T) as RuntimeType));
 		}
 
+#if !NETCORE
 		public static object GetUninitializedObject (Type type)
 		{
 			return FormatterServices.GetUninitializedObject (type);
 		}
+#endif
 	}
 }

+ 2 - 2
mcs/class/corlib/System.Runtime.InteropServices/GCHandle.cs

@@ -38,7 +38,7 @@ namespace System.Runtime.InteropServices
 {
 
 	[ComVisible(true)]
-	[MonoTODO("Struct should be [StructLayout(LayoutKind.Sequential)] but will need to be reordered for that.")]
+	// TODO Should be [StructLayout(LayoutKind.Sequential)] but will need to be reordered for that
 	public struct GCHandle 
 	{
 		// fields
@@ -77,7 +77,7 @@ namespace System.Runtime.InteropServices
 			get
 			{
 				if (!IsAllocated)
-					throw new InvalidOperationException (Locale.GetText ("Handle is not allocated"));
+					throw new InvalidOperationException ("Handle is not allocated");
 				return GetTarget (handle);
 			} 
 			set

+ 1 - 1
mcs/class/corlib/System.Threading/Interlocked.cs

@@ -38,7 +38,7 @@ using System.Runtime.ConstrainedExecution;
 
 namespace System.Threading
 {
-	public static class Interlocked 
+	public static partial class Interlocked
 	{
 		[ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
 		[MethodImplAttribute(MethodImplOptions.InternalCall)]

+ 2 - 0
mcs/class/corlib/System.Threading/Monitor.cs

@@ -31,7 +31,9 @@
 //
 
 using System.Runtime.CompilerServices;
+#if !DISABLE_REMOTING
 using System.Runtime.Remoting.Contexts;
+#endif
 using System.Runtime.ConstrainedExecution;
 using System.Runtime.InteropServices;
 

+ 3 - 3
mcs/class/corlib/System.Threading/NativeEventCalls.cs

@@ -35,12 +35,12 @@ using System;
 using System.Runtime.CompilerServices;
 using Microsoft.Win32.SafeHandles;
 
-#if !MOBILE
+#if !MOBILE && !NETCORE
 using System.Security.AccessControl;
 using System.IO;
 #endif
 
-namespace System.Threading 
+namespace System.Threading
 {
  	internal static class NativeEventCalls
 	{
@@ -87,7 +87,7 @@ namespace System.Threading
 		[MethodImplAttribute(MethodImplOptions.InternalCall)]
 		public static extern void CloseEvent_internal (IntPtr handle);
 
-#if !MOBILE
+#if !MOBILE && !NETCORE
 		public unsafe static IntPtr OpenEvent_internal (string name, EventWaitHandleRights rights, out int errorCode)
 		{
 			// FIXME check for embedded nuls in name

+ 26 - 23
mcs/class/corlib/System.Threading/Thread.cs

@@ -27,11 +27,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-using System.Runtime.Remoting.Contexts;
 using System.Runtime.Serialization;
-using System.Runtime.Serialization.Formatters.Binary;
-using System.Security.Permissions;
-using System.Security.Principal;
 using System.Globalization;
 using System.Runtime.CompilerServices;
 using System.Runtime.InteropServices;
@@ -42,6 +38,12 @@ using System.Security;
 using System.Diagnostics;
 using System.Runtime.ConstrainedExecution;
 
+#if !NETCORE
+using System.Runtime.Serialization.Formatters.Binary;
+using System.Runtime.Remoting.Contexts;
+using System.Security.Principal;
+#endif
+
 namespace System.Threading {
 	[StructLayout (LayoutKind.Sequential)]
 	sealed class InternalThread : CriticalFinalizerObject {
@@ -115,7 +117,10 @@ namespace System.Threading {
 	}
 
 	[StructLayout (LayoutKind.Sequential)]
-	public sealed partial class Thread {
+#if !NETCORE
+	public
+#endif
+	sealed partial class Thread {
 #pragma warning disable 414		
 		#region Sync with metadata/object-internals.h
 		private InternalThread internal_thread;
@@ -124,9 +129,6 @@ namespace System.Threading {
 		#endregion
 #pragma warning restore 414
 
-		IPrincipal principal;
-		int principal_version;
-
 		// the name of current_thread is
 		// important because they are used by the runtime.
 
@@ -151,13 +153,6 @@ namespace System.Threading {
 			}
 		}
 
-		public static Context CurrentContext {
-			[SecurityPermission (SecurityAction.LinkDemand, Infrastructure=true)]
-			get {
-				return(AppDomain.InternalGetContext ());
-			}
-		}
-
 		/*
 		 * These two methods return an array in the target
 		 * domain with the same content as the argument.  If
@@ -170,6 +165,16 @@ namespace System.Threading {
 		[MethodImplAttribute(MethodImplOptions.InternalCall)]
 		private extern static byte[] ByteArrayToCurrentDomain (byte[] arr);
 
+#if !NETCORE
+		IPrincipal principal;
+		int principal_version;
+
+		public static Context CurrentContext {
+			get {
+				return(AppDomain.InternalGetContext ());
+			}
+		}
+
 		static void DeserializePrincipal (Thread th)
 		{
 			MemoryStream ms = new MemoryStream (ByteArrayToCurrentDomain (th.Internal._serialized_principal));
@@ -266,7 +271,6 @@ namespace System.Threading {
 				th.principal_version = th.Internal._serialized_principal_version;
 				return th.principal;
 			}
-			[SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
 			set {
 				Thread th = CurrentThread;
 
@@ -288,6 +292,11 @@ namespace System.Threading {
 			}
 		}
 
+		public static AppDomain GetDomain() {
+			return AppDomain.CurrentDomain;
+		}
+#endif
+
 		[MethodImplAttribute(MethodImplOptions.InternalCall)]
 		private extern static Thread GetCurrentThread ();
 
@@ -308,10 +317,6 @@ namespace System.Threading {
 			}
 		}
 
-		public static AppDomain GetDomain() {
-			return AppDomain.CurrentDomain;
-		}
-
 		[MethodImplAttribute(MethodImplOptions.InternalCall)]
 		public extern static int GetDomainID();
 
@@ -418,13 +423,11 @@ namespace System.Threading {
 		[MethodImplAttribute(MethodImplOptions.InternalCall)]
 		private extern static void Abort_internal (InternalThread thread, object stateInfo);
 
-		[SecurityPermission (SecurityAction.Demand, ControlThread=true)]
 		public void Abort () 
 		{
 			Abort_internal (Internal, null);
 		}
 
-		[SecurityPermission (SecurityAction.Demand, ControlThread=true)]
 		public void Abort (object stateInfo) 
 		{
 			Abort_internal (Internal, stateInfo);
@@ -483,7 +486,7 @@ namespace System.Threading {
 			}
 		}
 
-		void StartInternal (IPrincipal principal, ref StackCrawlMark stackMark)
+		void StartInternal (object principal, ref StackCrawlMark stackMark)
 		{
 #if FEATURE_ROLE_BASED_SECURITY
 			Internal._serialized_principal = CurrentThread.Internal._serialized_principal;

+ 2 - 2
mcs/class/corlib/System.Threading/WaitHandle.cs

@@ -31,8 +31,9 @@
 using System;
 using System.Reflection;
 using System.Runtime.CompilerServices;
+#if !DISABLE_REMOTING
 using System.Runtime.Remoting.Contexts;
-using System.Security.Permissions;
+#endif
 using System.Runtime.InteropServices;
 using Microsoft.Win32.SafeHandles;
 using System.Runtime.ConstrainedExecution;
@@ -41,7 +42,6 @@ namespace System.Threading
 {
 	[StructLayout (LayoutKind.Sequential)]
 	public abstract partial class WaitHandle
-		: MarshalByRefObject, IDisposable
 	{
 		protected static readonly IntPtr InvalidHandle = (IntPtr) (-1);
 

+ 9 - 5
mcs/class/corlib/System/ArgIterator.cs

@@ -37,7 +37,11 @@ using System.Runtime.InteropServices;
 namespace System 
 {
 	[StructLayout (LayoutKind.Auto)]
-	public struct ArgIterator
+	public
+#if NETCORE
+	ref
+#endif
+	struct ArgIterator
 	{
 #pragma warning disable 169, 414
 		IntPtr sig;
@@ -73,7 +77,7 @@ namespace System
 
 		public override bool Equals (object o)
 		{
-			throw new NotSupportedException (Locale.GetText ("ArgIterator does not support Equals."));
+			throw new NotSupportedException ("ArgIterator does not support Equals.");
 		}
 
 		public override int GetHashCode ()
@@ -85,7 +89,7 @@ namespace System
 		public TypedReference GetNextArg ()
 		{
 			if (num_args == next_arg)
-				throw new InvalidOperationException (Locale.GetText ("Invalid iterator position."));
+				throw new InvalidOperationException ("Invalid iterator position.");
 			TypedReference result = new TypedReference ();
 			unsafe {
 				IntGetNextArg (&result);
@@ -100,7 +104,7 @@ namespace System
 		public TypedReference GetNextArg (RuntimeTypeHandle rth)
 		{
 			if (num_args == next_arg)
-				throw new InvalidOperationException (Locale.GetText ("Invalid iterator position."));
+				throw new InvalidOperationException ("Invalid iterator position.");
 			TypedReference result = new TypedReference ();
 			unsafe {
 				IntGetNextArgWithType (&result, rth.Value);
@@ -114,7 +118,7 @@ namespace System
 		public RuntimeTypeHandle GetNextArgType ()
 		{
 			if (num_args == next_arg)
-				throw new InvalidOperationException (Locale.GetText ("Invalid iterator position."));
+				throw new InvalidOperationException ("Invalid iterator position.");
 			return new RuntimeTypeHandle (IntGetNextArgType ());
 		}
 

+ 23 - 18
mcs/class/corlib/System/Array.cs

@@ -37,6 +37,10 @@ using System.Collections;
 using System.Runtime.CompilerServices;
 using System.Runtime.InteropServices;
 
+#if NETCORE
+using Internal.Runtime.CompilerServices;
+#endif
+
 using System.Collections.Generic;
 using System.Collections.ObjectModel;
 using System.Runtime.ConstrainedExecution;
@@ -106,7 +110,7 @@ namespace System
 		internal bool InternalArray__ICollection_Contains<T> (T item)
 		{
 			if (this.Rank > 1)
-				throw new RankException (Locale.GetText ("Only single dimension arrays are supported."));
+				throw new RankException ("Only single dimension arrays are supported.");
 
 			int length = this.Length;
 			for (int i = 0; i < length; i++) {
@@ -161,7 +165,7 @@ namespace System
 		internal int InternalArray__IndexOf<T> (T item)
 		{
 			if (this.Rank > 1)
-				throw new RankException (Locale.GetText ("Only single dimension arrays are supported."));
+				throw new RankException ("Only single dimension arrays are supported.");
 
 			int length = this.Length;
 			for (int i = 0; i < length; i++) {
@@ -364,8 +368,7 @@ namespace System
 
 			var lb  = GetLowerBound (0);
 			if (index < lb || index > GetUpperBound (0))
-				throw new IndexOutOfRangeException (Locale.GetText (
-					"Index has to be between upper and lower bound of the array."));
+				throw new IndexOutOfRangeException ("Index has to be between upper and lower bound of the array.");
 
 			if (GetType ().GetElementType ().IsPointer)
 				throw new NotSupportedException ("Type is not supported.");
@@ -392,8 +395,7 @@ namespace System
 
 			var lb  = GetLowerBound (0);
 			if (index < lb || index > GetUpperBound (0))
-				throw new IndexOutOfRangeException (Locale.GetText (
-					"Index has to be >= lower bound and <= upper bound of the array."));
+				throw new IndexOutOfRangeException ("Index has to be >= lower bound and <= upper bound of the array.");
 
 			if (GetType ().GetElementType ().IsPointer)
 				throw new NotSupportedException ("Type is not supported.");
@@ -490,18 +492,16 @@ namespace System
 				throw new NotSupportedException ("Array type can not be an open generic type");
 
 			if (lengths.Length < 1)
-				throw new ArgumentException (Locale.GetText ("Arrays must contain >= 1 elements."));
+				throw new ArgumentException ("Arrays must contain >= 1 elements.");
 
 			if (lengths.Length != lowerBounds.Length)
-				throw new ArgumentException (Locale.GetText ("Arrays must be of same size."));
+				throw new ArgumentException ("Arrays must be of same size.");
 
 			for (int j = 0; j < lowerBounds.Length; j ++) {
 				if (lengths [j] < 0)
-					throw new ArgumentOutOfRangeException ("lengths", Locale.GetText (
-						"Each value has to be >= 0."));
+					throw new ArgumentOutOfRangeException ("lengths", "Each value has to be >= 0.");
 				if ((long)lowerBounds [j] + (long)lengths [j] > (long)Int32.MaxValue)
-					throw new ArgumentOutOfRangeException ("lengths", Locale.GetText (
-						"Length + bound must not exceed Int32.MaxValue."));
+					throw new ArgumentOutOfRangeException ("lengths", "Length + bound must not exceed Int32.MaxValue.");
 			}
 
 			if (lengths.Length > 255)
@@ -558,19 +558,16 @@ namespace System
 				throw new ArgumentNullException ("destinationArray");
 
 			if (length < 0)
-				throw new ArgumentOutOfRangeException ("length", Locale.GetText (
-					"Value has to be >= 0."));;
+				throw new ArgumentOutOfRangeException ("length", "Value has to be >= 0.");
 
 			if (sourceArray.Rank != destinationArray.Rank)
 				throw new RankException(SR.Rank_MultiDimNotSupported);
 
 			if (sourceIndex < 0)
-				throw new ArgumentOutOfRangeException ("sourceIndex", Locale.GetText (
-					"Value has to be >= 0."));;
+				throw new ArgumentOutOfRangeException ("sourceIndex", "Value has to be >= 0.");
 
 			if (destinationIndex < 0)
-				throw new ArgumentOutOfRangeException ("destinationIndex", Locale.GetText (
-					"Value has to be >= 0."));;
+				throw new ArgumentOutOfRangeException ("destinationIndex", "Value has to be >= 0.");
 
 			if (FastCopy (sourceArray, sourceIndex, destinationArray, destinationIndex, length))
 				return;
@@ -670,12 +667,20 @@ namespace System
 
 		static int IndexOfImpl<T>(T[] array, T value, int startIndex, int count)
 		{
+#if NETCORE
+			throw new NotImplementedException ();
+#else
 			return EqualityComparer<T>.Default.IndexOf (array, value, startIndex, count);
+#endif
 		}
 
 		static int LastIndexOfImpl<T>(T[] array, T value, int startIndex, int count)
 		{
+#if NETCORE
+			throw new NotImplementedException ();
+#else
 			return EqualityComparer<T>.Default.LastIndexOf (array, value, startIndex, count);
+#endif
 		}
 
 		static void SortImpl (Array keys, Array items, int index, int length, IComparer comparer)

+ 3 - 5
mcs/class/corlib/System/Delegate.cs

@@ -47,8 +47,6 @@ namespace System
 		public bool curried_first_arg;
 	}
 
-	[ClassInterface (ClassInterfaceType.AutoDual)]
-	[System.Runtime.InteropServices.ComVisible (true)]
 	[Serializable]
 	[StructLayout (LayoutKind.Sequential)]
 	public abstract class Delegate : ICloneable, ISerializable
@@ -352,7 +350,7 @@ namespace System
 
 			for (Type targetType = target; targetType != null; targetType = targetType.BaseType) {
 				MethodInfo mi = targetType.GetMethod (method, flags,
-					null, delargtypes, EmptyArray<ParameterModifier>.Value);
+					null, delargtypes, Array.Empty<ParameterModifier>());
 				if (mi != null && return_type_match (invoke.ReturnType, mi.ReturnType)) {
 					info = mi;
 					break;
@@ -547,7 +545,7 @@ namespace System
 				return a;
 
 			if (a.GetType () != b.GetType ())
-				throw new ArgumentException (Locale.GetText ("Incompatible Delegate Types. First is {0} second is {1}.", a.GetType ().FullName, b.GetType ().FullName));
+				throw new ArgumentException (string.Format ("Incompatible Delegate Types. First is {0} second is {1}.", a.GetType ().FullName, b.GetType ().FullName));
 
 			return a.CombineImpl (b);
 		}
@@ -584,7 +582,7 @@ namespace System
 				return source;
 
 			if (source.GetType () != value.GetType ())
-				throw new ArgumentException (Locale.GetText ("Incompatible Delegate Types. First is {0} second is {1}.", source.GetType ().FullName, value.GetType ().FullName));
+				throw new ArgumentException (string.Format ("Incompatible Delegate Types. First is {0} second is {1}.", source.GetType ().FullName, value.GetType ().FullName));
 
 			return source.RemoveImpl (value);
 		}

Beberapa file tidak ditampilkan karena terlalu banyak file yang berubah dalam diff ini