// See the LICENSE file in the project root for more information.
using System;
+using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices.WindowsRuntime;
namespace Internal.Runtime.InteropServices.WindowsRuntime
/// Attach restricted error information to the exception if it may apply to that exception, returning
/// back the input value
/// </summary>
+ [return: NotNullIfNotNull("e")]
public static Exception? AttachRestrictedErrorInfo(Exception? e)
{
// If there is no exception, then the restricted error info doesn't apply to it
{
public abstract bool Initialize(string libpath, string reswFilename, out PRIExceptionInfo? exceptionInfo);
- public abstract string GetString(string stringName, string? startingCulture, string? neutralResourcesCulture);
+ public abstract string? GetString(string stringName, string? startingCulture, string? neutralResourcesCulture);
public abstract CultureInfo? GlobalResourceContextBestFitCultureInfo
{
{
public partial struct Point : IFormattable
{
- string IFormattable.ToString(string format, IFormatProvider provider) { throw null; }
+ string IFormattable.ToString(string? format, IFormatProvider? provider) { throw null; }
}
public partial struct Rect : IFormattable
{
- string IFormattable.ToString(string format, IFormatProvider provider) { throw null; }
+ string IFormattable.ToString(string? format, IFormatProvider? provider) { throw null; }
}
}
namespace Windows.UI
{
public partial struct Color : IFormattable
{
- string IFormattable.ToString(string format, IFormatProvider provider) { throw null; }
+ string IFormattable.ToString(string? format, IFormatProvider? provider) { throw null; }
}
}
public static System.Threading.Tasks.Task AsTask(this global::Windows.Foundation.IAsyncAction source) { throw null; }
public static System.Threading.Tasks.Task AsTask(this global::Windows.Foundation.IAsyncAction source, System.Threading.CancellationToken cancellationToken) { throw null; }
public static System.Threading.Tasks.Task AsTask<TProgress>(this global::Windows.Foundation.IAsyncActionWithProgress<TProgress> source) { throw null; }
- public static System.Threading.Tasks.Task AsTask<TProgress>(this global::Windows.Foundation.IAsyncActionWithProgress<TProgress> source, System.IProgress<TProgress> progress) { throw null; }
+ public static System.Threading.Tasks.Task AsTask<TProgress>(this global::Windows.Foundation.IAsyncActionWithProgress<TProgress> source, System.IProgress<TProgress>? progress) { throw null; }
public static System.Threading.Tasks.Task AsTask<TProgress>(this global::Windows.Foundation.IAsyncActionWithProgress<TProgress> source, System.Threading.CancellationToken cancellationToken) { throw null; }
- public static System.Threading.Tasks.Task AsTask<TProgress>(this global::Windows.Foundation.IAsyncActionWithProgress<TProgress> source, System.Threading.CancellationToken cancellationToken, System.IProgress<TProgress> progress) { throw null; }
+ public static System.Threading.Tasks.Task AsTask<TProgress>(this global::Windows.Foundation.IAsyncActionWithProgress<TProgress> source, System.Threading.CancellationToken cancellationToken, System.IProgress<TProgress>? progress) { throw null; }
public static System.Threading.Tasks.Task<TResult> AsTask<TResult>(this global::Windows.Foundation.IAsyncOperation<TResult> source) { throw null; }
public static System.Threading.Tasks.Task<TResult> AsTask<TResult>(this global::Windows.Foundation.IAsyncOperation<TResult> source, System.Threading.CancellationToken cancellationToken) { throw null; }
public static System.Threading.Tasks.Task<TResult> AsTask<TResult, TProgress>(this global::Windows.Foundation.IAsyncOperationWithProgress<TResult, TProgress> source) { throw null; }
- public static System.Threading.Tasks.Task<TResult> AsTask<TResult, TProgress>(this global::Windows.Foundation.IAsyncOperationWithProgress<TResult, TProgress> source, System.IProgress<TProgress> progress) { throw null; }
+ public static System.Threading.Tasks.Task<TResult> AsTask<TResult, TProgress>(this global::Windows.Foundation.IAsyncOperationWithProgress<TResult, TProgress> source, System.IProgress<TProgress>? progress) { throw null; }
public static System.Threading.Tasks.Task<TResult> AsTask<TResult, TProgress>(this global::Windows.Foundation.IAsyncOperationWithProgress<TResult, TProgress> source, System.Threading.CancellationToken cancellationToken) { throw null; }
- public static System.Threading.Tasks.Task<TResult> AsTask<TResult, TProgress>(this global::Windows.Foundation.IAsyncOperationWithProgress<TResult, TProgress> source, System.Threading.CancellationToken cancellationToken, System.IProgress<TProgress> progress) { throw null; }
+ public static System.Threading.Tasks.Task<TResult> AsTask<TResult, TProgress>(this global::Windows.Foundation.IAsyncOperationWithProgress<TResult, TProgress> source, System.Threading.CancellationToken cancellationToken, System.IProgress<TProgress>? progress) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public static System.Runtime.CompilerServices.TaskAwaiter GetAwaiter(this global::Windows.Foundation.IAsyncAction source) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
[System.CLSCompliantAttribute(false)]
public static global::Windows.Storage.Streams.IBuffer GetWindowsRuntimeBuffer(this System.IO.MemoryStream underlyingStream, int positionInStream, int length) { throw null; }
[System.CLSCompliantAttribute(false)]
- public static bool IsSameData(this global::Windows.Storage.Streams.IBuffer buffer, global::Windows.Storage.Streams.IBuffer otherBuffer) { throw null; }
+ public static bool IsSameData(this global::Windows.Storage.Streams.IBuffer buffer, global::Windows.Storage.Streams.IBuffer? otherBuffer) { throw null; }
[System.CLSCompliantAttribute(false)]
public static byte[] ToArray(this global::Windows.Storage.Streams.IBuffer source) { throw null; }
[System.CLSCompliantAttribute(false)]
public Point(double x, double y) { throw null; }
public double X { get { throw null; } set { } }
public double Y { get { throw null; } set { } }
- public override bool Equals(object o) { throw null; }
+ public override bool Equals(object? o) { throw null; }
public bool Equals(global::Windows.Foundation.Point value) { throw null; }
public override int GetHashCode() { throw null; }
public static bool operator ==(global::Windows.Foundation.Point point1, global::Windows.Foundation.Point point2) { throw null; }
public static bool operator !=(global::Windows.Foundation.Point point1, global::Windows.Foundation.Point point2) { throw null; }
public override string ToString() { throw null; }
- public string ToString(global::System.IFormatProvider provider) { throw null; }
+ public string ToString(global::System.IFormatProvider? provider) { throw null; }
}
public partial struct Rect : global::System.IFormattable
{
public double X { get { throw null; } set { } }
public double Y { get { throw null; } set { } }
public bool Contains(global::Windows.Foundation.Point point) { throw null; }
- public override bool Equals(object o) { throw null; }
+ public override bool Equals(object? o) { throw null; }
public bool Equals(global::Windows.Foundation.Rect value) { throw null; }
public override int GetHashCode() { throw null; }
public void Intersect(global::Windows.Foundation.Rect rect) { }
public static bool operator ==(global::Windows.Foundation.Rect rect1, global::Windows.Foundation.Rect rect2) { throw null; }
public static bool operator !=(global::Windows.Foundation.Rect rect1, global::Windows.Foundation.Rect rect2) { throw null; }
public override string ToString() { throw null; }
- public string ToString(global::System.IFormatProvider provider) { throw null; }
+ public string ToString(global::System.IFormatProvider? provider) { throw null; }
public void Union(global::Windows.Foundation.Point point) { }
public void Union(global::Windows.Foundation.Rect rect) { }
}
public double Height { get { throw null; } set { } }
public bool IsEmpty { get { throw null; } }
public double Width { get { throw null; } set { } }
- public override bool Equals(object o) { throw null; }
+ public override bool Equals(object? o) { throw null; }
public bool Equals(global::Windows.Foundation.Size value) { throw null; }
public override int GetHashCode() { throw null; }
public static bool operator ==(global::Windows.Foundation.Size size1, global::Windows.Foundation.Size size2) { throw null; }
public byte B { get { throw null; } set { } }
public byte G { get { throw null; } set { } }
public byte R { get { throw null; } set { } }
- public override bool Equals(object o) { throw null; }
+ public override bool Equals(object? o) { throw null; }
public bool Equals(global::Windows.UI.Color color) { throw null; }
public static global::Windows.UI.Color FromArgb(byte a, byte r, byte g, byte b) { throw null; }
public override int GetHashCode() { throw null; }
public static bool operator ==(global::Windows.UI.Color color1, global::Windows.UI.Color color2) { throw null; }
public static bool operator !=(global::Windows.UI.Color color1, global::Windows.UI.Color color2) { throw null; }
public override string ToString() { throw null; }
- public string ToString(global::System.IFormatProvider provider) { throw null; }
+ public string ToString(global::System.IFormatProvider? provider) { throw null; }
}
}
<NoWarn>$(NoWarn);1698</NoWarn>
<TargetFrameworks>$(NetCoreAppCurrent);netstandard2.0</TargetFrameworks>
<ExcludeCurrentNetCoreAppFromPackage>true</ExcludeCurrentNetCoreAppFromPackage>
+ <Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<Compile Include="System.Runtime.WindowsRuntime.cs" />
<DefineConstants Condition="'$(TargetsNetCoreApp)' == 'true'">$(DefineConstants);FEATURE_APPX</DefineConstants>
<TargetFrameworks>$(NetCoreAppCurrent)-Windows_NT;netstandard1.0;netstandard1.2;netstandard2.0</TargetFrameworks>
<ExcludeCurrentNetCoreAppFromPackage>true</ExcludeCurrentNetCoreAppFromPackage>
+ <Nullable>enable</Nullable>
</PropertyGroup>
<PropertyGroup Condition="'$(TargetsNetStandard)' == 'true'">
<GeneratePlatformNotSupportedAssemblyMessage>SR.PlatformNotSupported_WindowsRuntime</GeneratePlatformNotSupportedAssemblyMessage>
using System.Threading;
using Windows.Foundation;
using Windows.Storage.Streams;
+using System.Diagnostics.CodeAnalysis;
namespace System.IO
{
private static bool CanApplyReadMemoryStreamOptimization(Stream stream)
{
- MemoryStream memStream = stream as MemoryStream;
+ MemoryStream? memStream = stream as MemoryStream;
if (memStream == null)
return false;
#region Instance variables
- private Stream _managedStream = null;
+ private Stream? _managedStream = null;
private bool _leaveUnderlyingStreamOpen = true;
private readonly StreamReadOperationOptimization _readOptimization;
}
- public Stream GetManagedStream()
+ public Stream? GetManagedStream()
{
return _managedStream;
}
private Stream EnsureNotDisposed()
{
- Stream str = _managedStream;
+ Stream? str = _managedStream;
if (str == null)
{
/// <summary>Implements IDisposable.Dispose (IClosable.Close in WinRT)</summary>
void IDisposable.Dispose()
{
- Stream str = _managedStream;
+ Stream? str = _managedStream;
if (str == null)
return;
// for IRandonAccessStream.
// Cloning can be added in future, however, it would be quite complex
// to support it correctly for generic streams.
-
+ [DoesNotReturn]
private static void ThrowCloningNotSupported(string methodName)
{
NotSupportedException nse = new NotSupportedException(SR.Format(SR.NotSupported_CloningNotSupported, methodName));
using System.Threading;
using Windows.Foundation;
using Windows.Storage.Streams;
+using System.Diagnostics.CodeAnalysis;
namespace System.IO
{
internal abstract partial class StreamOperationAsyncResult : IAsyncResult
{
- private readonly AsyncCallback _userCompletionCallback = null;
- private readonly object _userAsyncStateInfo = null;
+ private readonly AsyncCallback? _userCompletionCallback = null;
+ private readonly object? _userAsyncStateInfo = null;
- private IAsyncInfo _asyncStreamOperation = null;
+ private IAsyncInfo? _asyncStreamOperation = null;
private volatile bool _completed = false;
private volatile bool _callbackInvoked = false;
- private volatile ManualResetEvent _waitHandle = null;
+ private volatile ManualResetEvent? _waitHandle = null;
private long _bytesCompleted = 0;
- private ExceptionDispatchInfo _errorInfo = null;
+ private ExceptionDispatchInfo? _errorInfo = null;
private readonly bool _processCompletedOperationInCallback;
- private IAsyncInfo _completedOperation = null;
+ private IAsyncInfo? _completedOperation = null;
protected internal StreamOperationAsyncResult(IAsyncInfo asyncStreamOperation,
- AsyncCallback userCompletionCallback, object userAsyncStateInfo,
+ AsyncCallback? userCompletionCallback, object? userAsyncStateInfo,
bool processCompletedOperationInCallback)
{
if (asyncStreamOperation == null)
}
- public object AsyncState
+ public object? AsyncState
{
get { return _userAsyncStateInfo; }
}
{
get
{
- ManualResetEvent wh = _waitHandle;
+ ManualResetEvent? wh = _waitHandle;
if (wh != null)
return wh;
// > Use 'completed' in the ctor - this way the handle wait will return as appropriate.
wh = new ManualResetEvent(_completed);
- ManualResetEvent otherHandle = Interlocked.CompareExchange(ref _waitHandle, wh, null);
+ ManualResetEvent? otherHandle = Interlocked.CompareExchange(ref _waitHandle, wh, null);
// We lost the race. Dispose OUR handle and return OTHER handle:
if (otherHandle != null)
internal abstract void ProcessConcreteCompletedOperation(IAsyncInfo completedOperation, out long bytesCompleted);
-
- private static void ProcessCompletedOperation_InvalidOperationThrowHelper(ExceptionDispatchInfo errInfo, string errMsg)
+ [DoesNotReturn]
+ private static void ProcessCompletedOperation_InvalidOperationThrowHelper(ExceptionDispatchInfo? errInfo, string errMsg)
{
- Exception errInfoSrc = (errInfo == null) ? null : errInfo.SourceException;
+ Exception? errInfoSrc = (errInfo == null) ? null : errInfo.SourceException;
if (errInfoSrc == null)
throw new InvalidOperationException(errMsg);
if (_completedOperation == null)
{
- ExceptionDispatchInfo errInfo = _errorInfo;
- Exception errInfoSrc = (errInfo == null) ? null : errInfo.SourceException;
+ ExceptionDispatchInfo? errInfo = _errorInfo;
+ Exception? errInfoSrc = (errInfo == null) ? null : errInfo.SourceException;
// See if errorInfo is set because we observed completedOperation == null previously (being slow is Ok on error path):
if (errInfoSrc != null && errInfoSrc is NullReferenceException
&& SR.NullReference_IOCompletionCallbackCannotProcessNullAsyncInfo.Equals(errInfoSrc.Message))
{
- errInfo.Throw();
+ errInfo!.Throw();
}
else
{
}
}
- if (_completedOperation.Id != _asyncStreamOperation.Id)
+ if (_completedOperation.Id != _asyncStreamOperation!.Id)
ProcessCompletedOperation_InvalidOperationThrowHelper(_errorInfo, SR.InvalidOperation_UnexpectedAsyncOperationID);
if (_completedOperation.Status == AsyncStatus.Error)
private void ThrowWithIOExceptionDispatchInfo(Exception e)
{
- WinRtIOHelper.NativeExceptionToIOExceptionInfo(ExceptionSupport.AttachRestrictedErrorInfo(_completedOperation.ErrorCode)).Throw();
+ WinRtIOHelper.NativeExceptionToIOExceptionInfo(ExceptionSupport.AttachRestrictedErrorInfo(_completedOperation!.ErrorCode)!).Throw();
}
} // class StreamOperationAsyncResult
internal class StreamReadAsyncResult : StreamOperationAsyncResult
{
- private readonly IBuffer _userBuffer = null;
+ private readonly IBuffer _userBuffer;
internal StreamReadAsyncResult(IAsyncOperationWithProgress<IBuffer, uint> asyncStreamReadOperation, IBuffer buffer,
- AsyncCallback userCompletionCallback, object userAsyncStateInfo,
+ AsyncCallback? userCompletionCallback, object? userAsyncStateInfo,
bool processCompletedOperationInCallback)
: base(asyncStreamReadOperation, userCompletionCallback, userAsyncStateInfo, processCompletedOperationInCallback)
IBuffer resultBuffer = completedOperation.GetResults();
Debug.Assert(resultBuffer != null);
- WinRtIOHelper.EnsureResultsInUserBuffer(_userBuffer, resultBuffer);
- bytesCompleted = _userBuffer.Length;
+ WinRtIOHelper.EnsureResultsInUserBuffer(_userBuffer!, resultBuffer);
+ bytesCompleted = _userBuffer!.Length;
}
} // class StreamReadAsyncResult
internal class StreamWriteAsyncResult : StreamOperationAsyncResult
{
internal StreamWriteAsyncResult(IAsyncOperationWithProgress<uint, uint> asyncStreamWriteOperation,
- AsyncCallback userCompletionCallback, object userAsyncStateInfo,
+ AsyncCallback? userCompletionCallback, object? userAsyncStateInfo,
bool processCompletedOperationInCallback)
: base(asyncStreamWriteOperation, userCompletionCallback, userAsyncStateInfo, processCompletedOperationInCallback)
// The user specified buffer will not have any data put into it:
buffer.Length = 0;
- MemoryStream memStream = stream as MemoryStream;
+ MemoryStream? memStream = stream as MemoryStream;
Debug.Assert(memStream != null);
try
// Note: the allocation costs we are paying for the new buffer are unavoidable anyway, as we would need to create
// an array to read into either way.
- IBuffer dataBuffer = buffer as WindowsRuntimeBuffer;
+ IBuffer? dataBuffer = buffer as WindowsRuntimeBuffer;
if (dataBuffer == null)
dataBuffer = WindowsRuntimeBuffer.Create((int)Math.Min((uint)int.MaxValue, buffer.Capacity));
dataBuffer.Length = 0;
// Get the buffer backing array:
- byte[] data;
+ byte[]? data;
int offset;
bool managedBufferAssert = dataBuffer.TryGetUnderlyingData(out data, out offset);
Debug.Assert(managedBufferAssert);
try
{
// Read asynchronously:
- bytesRead = await stream.ReadAsync(data, offset + bytesCompleted, bytesRequested - bytesCompleted, cancelToken)
+ bytesRead = await stream.ReadAsync(data!, offset + bytesCompleted, bytesRequested - bytesCompleted, cancelToken)
.ConfigureAwait(continueOnCapturedContext: false);
// We will continue here on a different thread when read async completed:
// Choose the optimal writing strategy for the kind of buffer supplied:
Func<CancellationToken, IProgress<uint>, Task<uint>> writeOperation;
- byte[] data;
+ byte[]? data;
int offset;
// If buffer is backed by a managed array:
using System.Threading;
using Windows.Foundation;
using Windows.Storage.Streams;
+using System.Diagnostics.CodeAnalysis;
namespace System.IO
{
#region Instance variables
- private byte[] _oneByteBuffer = null;
+ private byte[]? _oneByteBuffer = null;
private bool _leaveUnderlyingStreamOpen = true;
- private object _winRtStream;
+ private object? _winRtStream;
private readonly bool _canRead;
private readonly bool _canWrite;
private readonly bool _canSeek;
}
- public TWinRtStream GetWindowsRuntimeStream<TWinRtStream>() where TWinRtStream : class
+ public TWinRtStream? GetWindowsRuntimeStream<TWinRtStream>() where TWinRtStream : class
{
- object wrtStr = _winRtStream;
+ object? wrtStr = _winRtStream;
if (wrtStr == null)
return null;
{
get
{
- byte[] obb = _oneByteBuffer;
+ byte[]? obb = _oneByteBuffer;
if (obb == null) // benign race for multiple init
_oneByteBuffer = obb = new byte[1];
return obb;
}
}
-
-#if DEBUG
- private static void AssertValidStream(object winRtStream)
- {
- Debug.Assert(winRtStream != null,
- "This to-NetFx Stream adapter must not be disposed and the underlying WinRT stream must be of compatible type for this operation");
- }
-#endif // DEBUG
-
-
- private TWinRtStream EnsureNotDisposed<TWinRtStream>() where TWinRtStream : class
+ private TWinRtStream? EnsureNotDisposed<TWinRtStream>() where TWinRtStream : class
{
- object wrtStr = _winRtStream;
+ object? wrtStr = _winRtStream;
if (wrtStr == null)
throw new ObjectDisposedException(SR.ObjectDisposed_CannotPerformOperation);
// WinRT streams should implement IDisposable (IClosable in WinRT), but let's be defensive:
if (disposing && _winRtStream != null && !_leaveUnderlyingStreamOpen)
{
- IDisposable disposableWinRtStream = _winRtStream as IDisposable; // benign race on winRtStream
+ IDisposable? disposableWinRtStream = _winRtStream as IDisposable; // benign race on winRtStream
if (disposableWinRtStream != null)
disposableWinRtStream.Dispose();
}
{
get
{
- IRandomAccessStream wrtStr = EnsureNotDisposed<IRandomAccessStream>();
+ IRandomAccessStream? wrtStr = EnsureNotDisposed<IRandomAccessStream>();
if (!_canSeek)
throw new NotSupportedException(SR.NotSupported_CannotUseLength_StreamNotSeekable);
-#if DEBUG
- AssertValidStream(wrtStr);
-#endif // DEBUG
+ Debug.Assert(wrtStr != null);
ulong size = wrtStr.Size;
{
get
{
- IRandomAccessStream wrtStr = EnsureNotDisposed<IRandomAccessStream>();
+ IRandomAccessStream? wrtStr = EnsureNotDisposed<IRandomAccessStream>();
if (!_canSeek)
throw new NotSupportedException(SR.NotSupported_CannotUsePosition_StreamNotSeekable);
-#if DEBUG
- AssertValidStream(wrtStr);
-#endif // DEBUG
+ Debug.Assert(wrtStr != null);
ulong pos = wrtStr.Position;
if (value < 0)
throw new ArgumentOutOfRangeException(nameof(Position), SR.ArgumentOutOfRange_IO_CannotSeekToNegativePosition);
- IRandomAccessStream wrtStr = EnsureNotDisposed<IRandomAccessStream>();
+ IRandomAccessStream? wrtStr = EnsureNotDisposed<IRandomAccessStream>();
if (!_canSeek)
throw new NotSupportedException(SR.NotSupported_CannotUsePosition_StreamNotSeekable);
-#if DEBUG
- AssertValidStream(wrtStr);
-#endif // DEBUG
+ Debug.Assert(wrtStr != null);
wrtStr.Seek(unchecked((ulong)value));
}
public override long Seek(long offset, SeekOrigin origin)
{
- IRandomAccessStream wrtStr = EnsureNotDisposed<IRandomAccessStream>();
+ IRandomAccessStream? wrtStr = EnsureNotDisposed<IRandomAccessStream>();
if (!_canSeek)
throw new NotSupportedException(SR.NotSupported_CannotSeekInStream);
-#if DEBUG
- AssertValidStream(wrtStr);
-#endif // DEBUG
+ Debug.Assert(wrtStr != null);
switch (origin)
{
if (value < 0)
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_CannotResizeStreamToNegative);
- IRandomAccessStream wrtStr = EnsureNotDisposed<IRandomAccessStream>();
+ IRandomAccessStream? wrtStr = EnsureNotDisposed<IRandomAccessStream>();
if (!_canSeek)
throw new NotSupportedException(SR.NotSupported_CannotSeekInStream);
EnsureCanWrite();
-#if DEBUG
- AssertValidStream(wrtStr);
-#endif // DEBUG
+ Debug.Assert(wrtStr != null);
wrtStr.Size = unchecked((ulong)value);
#region Reading
- private IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state, bool usedByBlockingWrapper)
+ private IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state, bool usedByBlockingWrapper)
{
// This method is somewhat tricky: We could consider just calling ReadAsync (recall that Task implements IAsyncResult).
// It would be OK for cases where BeginRead is invoked directly by the public user.
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InsufficientSpaceInTargetBuffer);
- IInputStream wrtStr = EnsureNotDisposed<IInputStream>();
+ IInputStream? wrtStr = EnsureNotDisposed<IInputStream>();
EnsureCanRead();
-#if DEBUG
- AssertValidStream(wrtStr);
-#endif // DEBUG
+ Debug.Assert(wrtStr != null);
IBuffer userBuffer = buffer.AsBuffer(offset, count);
IAsyncOperationWithProgress<IBuffer, uint> asyncReadOperation = wrtStr.ReadAsync(userBuffer,
EnsureNotDisposed();
EnsureCanRead();
- StreamOperationAsyncResult streamAsyncResult = asyncResult as StreamOperationAsyncResult;
+ StreamOperationAsyncResult? streamAsyncResult = asyncResult as StreamOperationAsyncResult;
if (streamAsyncResult == null)
throw new ArgumentException(SR.Argument_UnexpectedAsyncResult, nameof(asyncResult));
#region Writing
- public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
+ public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state)
{
return BeginWrite(buffer, offset, count, callback, state, usedByBlockingWrapper: false);
}
- private IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state, bool usedByBlockingWrapper)
+ private IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state, bool usedByBlockingWrapper)
{
// See the large comment in BeginRead about why we are not using this.WriteAsync,
// and instead using a custom implementation of IAsyncResult.
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InsufficientArrayElementsAfterOffset);
- IOutputStream wrtStr = EnsureNotDisposed<IOutputStream>();
+ IOutputStream? wrtStr = EnsureNotDisposed<IOutputStream>();
EnsureCanWrite();
-#if DEBUG
- AssertValidStream(wrtStr);
-#endif // DEBUG
+ Debug.Assert(wrtStr != null);
IBuffer asyncWriteBuffer = buffer.AsBuffer(offset, count);
EnsureNotDisposed();
EnsureCanWrite();
- StreamOperationAsyncResult streamAsyncResult = asyncResult as StreamOperationAsyncResult;
+ StreamOperationAsyncResult? streamAsyncResult = asyncResult as StreamOperationAsyncResult;
if (streamAsyncResult == null)
throw new ArgumentException(SR.Argument_UnexpectedAsyncResult, nameof(asyncResult));
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InsufficientArrayElementsAfterOffset);
- IOutputStream wrtStr = EnsureNotDisposed<IOutputStream>();
+ IOutputStream? wrtStr = EnsureNotDisposed<IOutputStream>();
EnsureCanWrite();
-#if DEBUG
- AssertValidStream(wrtStr);
-#endif // DEBUG
+ Debug.Assert(wrtStr != null);
// If already cancelled, bail early:
cancellationToken.ThrowIfCancellationRequested();
// See the large comment in BeginRead about why we are not using this.FlushAsync,
// and instead using a custom implementation of IAsyncResult.
- IOutputStream wrtStr = EnsureNotDisposed<IOutputStream>();
+ IOutputStream? wrtStr = EnsureNotDisposed<IOutputStream>();
// Calling Flush in a non-writable stream is a no-op, not an error:
if (!_canWrite)
return;
-#if DEBUG
- AssertValidStream(wrtStr);
-#endif // DEBUG
+ Debug.Assert(wrtStr != null);
IAsyncOperation<bool> asyncFlushOperation = wrtStr.FlushAsync();
StreamFlushAsyncResult asyncResult = new StreamFlushAsyncResult(asyncFlushOperation, processCompletedOperationInCallback: false);
public override Task FlushAsync(CancellationToken cancellationToken)
{
- IOutputStream wrtStr = EnsureNotDisposed<IOutputStream>();
+ IOutputStream? wrtStr = EnsureNotDisposed<IOutputStream>();
// Calling Flush in a non-writable stream is a no-op, not an error:
if (!_canWrite)
return Task.CompletedTask;
-#if DEBUG
- AssertValidStream(wrtStr);
-#endif // DEBUG
+ Debug.Assert(wrtStr != null);
cancellationToken.ThrowIfCancellationRequested();
Debug.Assert(buffer.Length - offset >= count);
Debug.Assert(_canRead);
- IInputStream wrtStr = EnsureNotDisposed<IInputStream>();
+ IInputStream? wrtStr = EnsureNotDisposed<IInputStream>();
-#if DEBUG
- AssertValidStream(wrtStr);
-#endif // DEBUG
+ Debug.Assert(wrtStr != null);
try
{
}
[CLSCompliant(false)]
- public static SafeFileHandle CreateSafeFileHandle(
+ public static SafeFileHandle? CreateSafeFileHandle(
this IStorageFile windowsRuntimeFile,
FileAccess access = FileAccess.ReadWrite,
FileShare share = FileShare.Read,
HANDLE_SHARING_OPTIONS sharingOptions = FileShareToHandleSharingOptions(share);
HANDLE_OPTIONS handleOptions = FileOptionsToHandleOptions(options);
- IStorageItemHandleAccess handleAccess = ((object)windowsRuntimeFile) as IStorageItemHandleAccess;
+ IStorageItemHandleAccess? handleAccess = ((object)windowsRuntimeFile) as IStorageItemHandleAccess;
if (handleAccess == null)
return null;
}
[CLSCompliant(false)]
- public static SafeFileHandle CreateSafeFileHandle(
+ public static SafeFileHandle? CreateSafeFileHandle(
this IStorageFolder rootDirectory,
string relativePath,
FileMode mode)
}
[CLSCompliant(false)]
- public static SafeFileHandle CreateSafeFileHandle(
+ public static SafeFileHandle? CreateSafeFileHandle(
this IStorageFolder rootDirectory,
string relativePath,
FileMode mode,
HANDLE_SHARING_OPTIONS sharingOptions = FileShareToHandleSharingOptions(share);
HANDLE_OPTIONS handleOptions = FileOptionsToHandleOptions(options);
- IStorageFolderHandleAccess handleAccess = ((object)rootDirectory) as IStorageFolderHandleAccess;
+ IStorageFolderHandleAccess? handleAccess = ((object)rootDirectory) as IStorageFolderHandleAccess;
if (handleAccess == null)
return null;
where TKey : class
where TValue : class
{
- TValue valueInMap;
+ TValue? valueInMap;
Debug.Assert(key != null);
if (valueMayBeWrappedInBufferedStream)
{
- BufferedStream bufferedValueInMap = valueInMap as BufferedStream;
+ BufferedStream? bufferedValueInMap = valueInMap as BufferedStream;
Debug.Assert(object.ReferenceEquals(value, valueInMap)
|| (bufferedValueInMap != null && object.ReferenceEquals(value, bufferedValueInMap.UnderlyingStream)));
}
Debug.Assert(!string.IsNullOrWhiteSpace(methodName));
int currentBufferSize = 0;
- BufferedStream bufferedAdapter = adapter as BufferedStream;
+ BufferedStream? bufferedAdapter = adapter as BufferedStream;
if (bufferedAdapter != null)
currentBufferSize = bufferedAdapter.BufferSize;
// We currently do capability-based adapter selection for WinRt->NetFx, but not vice versa (time constraints).
// Once we added the reverse direction, we will be able replce this entire section with just a few lines.
- NetFxToWinRtStreamAdapter sAdptr = windowsRuntimeStream as NetFxToWinRtStreamAdapter;
+ NetFxToWinRtStreamAdapter? sAdptr = windowsRuntimeStream as NetFxToWinRtStreamAdapter;
if (sAdptr != null)
{
- Stream wrappedNetFxStream = sAdptr.GetManagedStream();
+ Stream? wrappedNetFxStream = sAdptr.GetManagedStream();
if (wrappedNetFxStream == null)
throw new ObjectDisposedException(nameof(windowsRuntimeStream), SR.ObjectDisposed_CannotPerformOperation);
// We have a real WinRT stream.
- Stream adapter;
+ Stream? adapter;
bool adapterExists = s_winRtToNetFxAdapterMap.TryGetValue(windowsRuntimeStream, out adapter);
// There is already an adapter:
if (forceBufferSize)
EnsureAdapterBufferSize(adapter, bufferSize, invokedMethodName);
- WinRtToNetFxStreamAdapter actualAdapter = adapter as WinRtToNetFxStreamAdapter;
+ WinRtToNetFxStreamAdapter? actualAdapter = adapter as WinRtToNetFxStreamAdapter;
if (actualAdapter == null)
actualAdapter = ((BufferedStream)adapter).UnderlyingStream as WinRtToNetFxStreamAdapter;
- actualAdapter.SetWonInitializationRace();
+ actualAdapter!.SetWonInitializationRace();
return adapter;
}
object adapter = AsWindowsRuntimeStreamInternal(stream);
- IInputStream winRtStream = adapter as IInputStream;
+ IInputStream? winRtStream = adapter as IInputStream;
Debug.Assert(winRtStream != null);
return winRtStream;
object adapter = AsWindowsRuntimeStreamInternal(stream);
- IOutputStream winRtStream = adapter as IOutputStream;
+ IOutputStream? winRtStream = adapter as IOutputStream;
Debug.Assert(winRtStream != null);
return winRtStream;
object adapter = AsWindowsRuntimeStreamInternal(stream);
- IRandomAccessStream winRtStream = adapter as IRandomAccessStream;
+ IRandomAccessStream? winRtStream = adapter as IRandomAccessStream;
Debug.Assert(winRtStream != null);
return winRtStream;
{
// Check to see if the managed stream is actually a wrapper of a WinRT stream:
// (This can be either an adapter directly, or an adapter wrapped in a BufferedStream.)
- WinRtToNetFxStreamAdapter sAdptr = stream as WinRtToNetFxStreamAdapter;
+ WinRtToNetFxStreamAdapter? sAdptr = stream as WinRtToNetFxStreamAdapter;
if (sAdptr == null)
{
- BufferedStream buffAdptr = stream as BufferedStream;
+ BufferedStream? buffAdptr = stream as BufferedStream;
if (buffAdptr != null)
sAdptr = buffAdptr.UnderlyingStream as WinRtToNetFxStreamAdapter;
}
// In that case we do not need to put the wrapper into the map.
if (sAdptr != null)
{
- object wrappedWinRtStream = sAdptr.GetWindowsRuntimeStream<object>();
+ object? wrappedWinRtStream = sAdptr.GetWindowsRuntimeStream<object>();
if (wrappedWinRtStream == null)
throw new ObjectDisposedException(nameof(stream), SR.ObjectDisposed_CannotPerformOperation);
// We have a real managed Stream.
// See if the managed stream already has an adapter:
- NetFxToWinRtStreamAdapter adapter;
+ NetFxToWinRtStreamAdapter? adapter;
bool adapterExists = s_netFxToWinRtAdapterMap.TryGetValue(stream, out adapter);
// There is already an adapter:
if (adapterExists)
- return adapter;
+ return adapter!;
// We do not have an adapter for this managed stream yet and we need to create one.
// Do that in a thread-safe manner in a separate method such that we only have to pay for the compiler allocating
// invariant name is an empty string. We will use the private invariant culture name x-VL instead.
private const string c_InvariantCulturePrivateName = "x-VL";
- private ResourceMap _resourceMap;
- private ResourceContext _clonedResourceContext;
- private string _clonedResourceContextFallBackList;
+ private ResourceMap? _resourceMap;
+ private ResourceContext? _clonedResourceContext;
+ private string? _clonedResourceContextFallBackList;
- private static char[] s_charCultureSeparator;
+ private static char[]? s_charCultureSeparator;
private struct PackageInfo
{
- public string Path;
- public string Name;
- public string FullName;
+ public string? Path;
+ public string? Name;
+ public string? FullName;
}
private static PackageInfo s_currentPackageInfo;
- private static List<PackageInfo> s_dependentPackageInfoList;
+ private static List<PackageInfo>? s_dependentPackageInfoList;
- private static ResourceContext s_globalResourceContext; // Read from it but do not modify it or call Reset() on it as that would affect the app-wide state
+ private static ResourceContext? s_globalResourceContext; // Read from it but do not modify it or call Reset() on it as that would affect the app-wide state
- private static volatile string s_globalResourceContextFallBackList;
- private static volatile CultureInfo s_globalResourceContextBestFitCultureInfo;
- private static volatile global::Windows.ApplicationModel.Resources.Core.ResourceManager s_globalResourceManager;
+ private static volatile string? s_globalResourceContextFallBackList;
+ private static volatile CultureInfo? s_globalResourceContextBestFitCultureInfo;
+ private static volatile global::Windows.ApplicationModel.Resources.Core.ResourceManager? s_globalResourceManager;
private static readonly object s_objectForLock = new object(); // Used by InitializeStatics
private static bool InitializeStatics()
{
- global::Windows.ApplicationModel.Resources.Core.ResourceManager globalResourceManager = null;
+ global::Windows.ApplicationModel.Resources.Core.ResourceManager? globalResourceManager = null;
if (s_globalResourceManager == null)
{
return s_globalResourceManager != null;
}
- private static void InitializeStaticGlobalResourceContext(global::Windows.ApplicationModel.Resources.Core.ResourceManager resourceManager)
+ private static void InitializeStaticGlobalResourceContext(global::Windows.ApplicationModel.Resources.Core.ResourceManager? resourceManager)
{
if (s_globalResourceContext == null)
{
// Returns the CultureInfo representing the first language in the list that we can construct a CultureInfo for or null if
// no such culture exists.
- private static unsafe CultureInfo GetBestFitCultureFromLanguageList(List<string> languages)
+ private static unsafe CultureInfo? GetBestFitCultureFromLanguageList(List<string> languages)
{
char* localeNameBuffer = stackalloc char[Interop.Kernel32.LOCALE_NAME_MAX_LENGTH]; // LOCALE_NAME_MAX_LENGTH includes null terminator
}
#endif
- private static string FindPackageSimpleNameForFilename(string libpath)
+ private static string? FindPackageSimpleNameForFilename(string libpath)
{
Debug.Assert(libpath != null);
Debug.Assert(s_currentPackageInfo.Path != null); // Set in InitializeStatics()
InitializeStaticsForDependentPackages();
// s_dependentPackageInfoList is empty (but non-null) if there are no dependent packages.
- foreach (PackageInfo dependentPackageInfo in s_dependentPackageInfoList)
+ foreach (PackageInfo dependentPackageInfo in s_dependentPackageInfoList!)
{
- if (LibpathMatchesPackagepath(libpath, dependentPackageInfo.Path))
+ if (LibpathMatchesPackagepath(libpath, dependentPackageInfo.Path!))
return dependentPackageInfo.Name; // This may be null, in which case we failed to get the name (in InitializeStaticsForDependentPackages), but matched the path, so stop looking.
}
}
package name as subfolder in its path. Based on this assumption we can find the package
to which an NI belongs. Below code does that.
*/
- if (LibpathContainsPackagename(libpath, s_currentPackageInfo.FullName))
+ if (LibpathContainsPackagename(libpath, s_currentPackageInfo.FullName!))
return s_currentPackageInfo.Name;
else // Look at dependent packages
{
// s_dependentPackageInfoList is empty (but non-null) if there are no dependent packages.
foreach (PackageInfo dependentPackageInfo in s_dependentPackageInfoList)
{
- if (LibpathContainsPackagename(libpath, dependentPackageInfo.FullName))
+ if (LibpathContainsPackagename(libpath, dependentPackageInfo.FullName!))
return dependentPackageInfo.Name;
}
}
// Only returns true if the function succeeded completely.
// Outputs exceptionInfo since it may be needed for debugging purposes
// if an exception is thrown by one of Initialize's callees.
- public override bool Initialize(string libpath, string reswFilename, out PRIExceptionInfo exceptionInfo)
+ public override bool Initialize(string libpath, string reswFilename, out PRIExceptionInfo? exceptionInfo)
{
Debug.Assert(libpath != null);
Debug.Assert(reswFilename != null);
// reliable information to include in it.
IReadOnlyDictionary<string, ResourceMap>
- resourceMapDictionary = s_globalResourceManager.AllResourceMaps;
+ resourceMapDictionary = s_globalResourceManager!.AllResourceMaps;
if (resourceMapDictionary != null)
{
- string packageSimpleName = FindPackageSimpleNameForFilename(libpath);
+ string? packageSimpleName = FindPackageSimpleNameForFilename(libpath);
#if NETSTANDARD2_0 || NETCOREAPP
// If we have found a simple package name for the assembly, lets make sure it is not *.resource.dll that
#endif
if (packageSimpleName != null)
{
- ResourceMap packageResourceMap = null;
+ ResourceMap? packageResourceMap = null;
// Win8 enforces that package simple names are unique (for example, the App Store will not
// allow two apps with the same package simple name). That is why the Modern Resource Manager
// GetSubtree returns null when it cannot find resource strings
// named "reswFilename/*" for the package we are looking up.
- reswFilename = UriUtility.UriEncode(reswFilename);
+ reswFilename = UriUtility.UriEncode(reswFilename)!;
_resourceMap = packageResourceMap.GetSubtree(reswFilename);
if (_resourceMap == null)
}
else
{
- _clonedResourceContext = s_globalResourceContext.Clone();
+ _clonedResourceContext = s_globalResourceContext!.Clone();
if (_clonedResourceContext != null)
{
get
{
InitializeStaticGlobalResourceContext(null);
- return s_globalResourceContextBestFitCultureInfo;
+ return s_globalResourceContextBestFitCultureInfo!;
}
}
// continue to be thread-safe.
// Throws exceptions
- public override string GetString(string stringName,
- string startingCulture, string neutralResourcesCulture)
+ public override string? GetString(string stringName, string? startingCulture, string? neutralResourcesCulture)
{
Debug.Assert(stringName != null);
Debug.Assert(_resourceMap != null); // Should have been initialized by now
- ResourceCandidate resourceCandidate = null;
+ ResourceCandidate? resourceCandidate = null;
- stringName = UriUtility.UriEncode(stringName);
+ stringName = UriUtility.UriEncode(stringName)!;
if (startingCulture == null && neutralResourcesCulture == null)
{
// The starting culture has to be looked up first, and neutral resources culture has
// to be looked up last.
- string newResourceFallBackList = null;
+ string? newResourceFallBackList = null;
newResourceFallBackList =
(startingCulture == null ? "" : startingCulture + ";") +
// Adapted from the UrlEncode methods originally
// in file:ndp\fx\src\xsp\system\web\httpserverutility.cs
// and file:ndp\fx\src\xsp\system\web\util\httpencoder.cs
- public static string UriEncode(string str)
+ public static string? UriEncode(string str)
{
if (str == null)
return null;
cBytesToEncode++;
}
- byte[] expandedBytes = null;
+ byte[]? expandedBytes = null;
// nothing to expand?
if (cBytesToEncode == 0)
// The return type for this function is actually an INotifyCollectionChangedEventArgs*
// but we need to make sure we don't accidentally project our native object back to managed
// when marshalling it to native (which happens when correctly typing the return type as an INotifyCollectionChangedEventArgs).
- IntPtr CreateInstanceWithAllParameters(int action, IList newItems, IList oldItems, int newIndex, int oldIndex, object outer, ref object inner);
+ IntPtr CreateInstanceWithAllParameters(int action, IList? newItems, IList? oldItems, int newIndex, int oldIndex, object? outer, ref object? inner);
}
// Local definition of Windows.UI.Xaml.Data.INotifyCollectionChangedEventArgsFactory
// The return type for this function is actually an IPropertyChangedEventArgs*
// but we need to make sure we don't accidentally project our native object back to managed
// when marshalling it to native (which happens when correctly typing the return type as an IPropertyChangedEventArgs).
- IntPtr CreateInstance(string name, object outer, ref object inner);
+ IntPtr CreateInstance(string? name, object? outer, ref object? inner);
}
internal static class NotifyCollectionChangedEventArgsMarshaler
{
private const string WinRTNotifyCollectionChangedEventArgsName = "Windows.UI.Xaml.Interop.NotifyCollectionChangedEventArgs";
- private static INotifyCollectionChangedEventArgsFactory s_EventArgsFactory;
+ private static INotifyCollectionChangedEventArgsFactory? s_EventArgsFactory;
// Extracts properties from a managed NotifyCollectionChangedEventArgs and passes them to
// a VM-implemented helper that creates a WinRT NotifyCollectionChangedEventArgs instance.
if (s_EventArgsFactory == null)
{
- object factory = null;
+ object? factory = null;
Guid guid = typeof(INotifyCollectionChangedEventArgsFactory).GUID;
int hr = Interop.mincore.RoGetActivationFactory(WinRTNotifyCollectionChangedEventArgsName, ref guid, out factory);
if (hr < 0)
s_EventArgsFactory = (INotifyCollectionChangedEventArgsFactory)factory;
}
- object inner = null;
+ object? inner = null;
return s_EventArgsFactory.CreateInstanceWithAllParameters((int)managedArgs.Action, managedArgs.NewItems, managedArgs.OldItems, managedArgs.NewStartingIndex, managedArgs.OldStartingIndex, null, ref inner);
}
// Extracts properties from a WinRT NotifyCollectionChangedEventArgs and creates a new
// managed NotifyCollectionChangedEventArgs instance.
// This method is called from IL stubs and needs to have its token stabilized.
- internal static NotifyCollectionChangedEventArgs ConvertToManaged(IntPtr nativeArgsIP)
+ internal static NotifyCollectionChangedEventArgs? ConvertToManaged(IntPtr nativeArgsIP)
{
if (nativeArgsIP == IntPtr.Zero)
return null;
{
private const string WinRTPropertyChangedEventArgsName = "Windows.UI.Xaml.Data.PropertyChangedEventArgs";
- private static IPropertyChangedEventArgsFactory s_pPCEventArgsFactory;
+ private static IPropertyChangedEventArgsFactory? s_pPCEventArgsFactory;
// Extracts PropertyName from a managed PropertyChangedEventArgs and passes them to
// a VM-implemented helper that creates a WinRT PropertyChangedEventArgs instance.
if (s_pPCEventArgsFactory == null)
{
- object factory = null;
+ object? factory = null;
Guid guid = typeof(IPropertyChangedEventArgsFactory).GUID;
int hr = Interop.mincore.RoGetActivationFactory(WinRTPropertyChangedEventArgsName, ref guid, out factory);
if (hr < 0)
s_pPCEventArgsFactory = (IPropertyChangedEventArgsFactory)factory;
}
- object inner = null;
+ object? inner = null;
return s_pPCEventArgsFactory.CreateInstance(managedArgs.PropertyName, null, ref inner);
}
// Extracts properties from a WinRT PropertyChangedEventArgs and creates a new
// managed PropertyChangedEventArgs instance.
// This method is called from IL stubs and needs to have its token stabilized.
- internal static PropertyChangedEventArgs ConvertToManaged(IntPtr nativeArgsIP)
+ internal static PropertyChangedEventArgs? ConvertToManaged(IntPtr nativeArgsIP)
{
if (nativeArgsIP == IntPtr.Zero)
return null;
INotifyCollectionChanged _this = Unsafe.As<INotifyCollectionChanged>(this);
EventRegistrationTokenTable<NotifyCollectionChangedEventHandler> table = s_weakTable.GetOrCreateValue(_this);
- if (table.RemoveEventHandler(token, out NotifyCollectionChangedEventHandler handler))
+ if (table.RemoveEventHandler(token, out NotifyCollectionChangedEventHandler? handler))
{
_this.CollectionChanged -= handler;
}
INotifyPropertyChanged _this = Unsafe.As<INotifyPropertyChanged>(this);
EventRegistrationTokenTable<PropertyChangedEventHandler> table = s_weakTable.GetOrCreateValue(_this);
- if (table.RemoveEventHandler(token, out PropertyChangedEventHandler handler))
+ if (table.RemoveEventHandler(token, out PropertyChangedEventHandler? handler))
{
_this.PropertyChanged -= handler;
}
ICommand _this = Unsafe.As<ICommand>(this);
EventRegistrationTokenTable<EventHandler> table = s_weakTable.GetOrCreateValue(_this);
- if (table.RemoveEventHandler(token, out EventHandler handler))
+ if (table.RemoveEventHandler(token, out EventHandler? handler))
{
_this.CanExecuteChanged -= handler;
}
{
// Check whether it is a round-tripping case i.e. the sender is of the type eventArgs,
// If so we use it else we pass EventArgs.Empty
- return (object sender, object e) =>
+ return (object? sender, object e) =>
{
- EventArgs eventArgs = e as EventArgs;
+ EventArgs? eventArgs = e as EventArgs;
handler(sender, (eventArgs == null ? System.EventArgs.Empty : eventArgs));
};
}
internal static EventHandler CreateWrapperHandler(EventHandler<object> handler)
{
- return (object sender, EventArgs e) => handler(sender, e);
+ return (object? sender, EventArgs e) => handler(sender, e);
}
internal static EventHandler<object> GetValueFromEquivalentKey(
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
// This object handles IMarshal calls for us:
[ThreadStatic]
- private static IMarshal t_winRtMarshalProxy = null;
+ private static IMarshal? t_winRtMarshalProxy = null;
private static void EnsureHasMarshalProxy()
{
#region Fields
- private readonly byte[] _data = null;
+ private readonly byte[] _data;
private readonly int _dataStartOffs = 0;
private int _usefulDataLength = 0;
private readonly int _maxDataCapacity = 0;
#region Helpers
- internal void GetUnderlyingData(out byte[] underlyingDataArray, out int underlyingDataArrayStartOffset)
+ internal void GetUnderlyingData([NotNull] out byte[]? underlyingDataArray, out int underlyingDataArrayStartOffset)
{
- underlyingDataArray = _data;
+ underlyingDataArray = _data!;
underlyingDataArrayStartOffset = _dataStartOffs;
}
void IMarshal.DisconnectObject(uint dwReserved)
{
EnsureHasMarshalProxy();
- t_winRtMarshalProxy.DisconnectObject(dwReserved);
+ t_winRtMarshalProxy!.DisconnectObject(dwReserved);
}
void IMarshal.GetMarshalSizeMax(ref Guid riid, IntPtr pv, uint dwDestContext, IntPtr pvDestContext, uint mshlflags, out uint pSize)
{
EnsureHasMarshalProxy();
- t_winRtMarshalProxy.GetMarshalSizeMax(ref riid, pv, dwDestContext, pvDestContext, mshlflags, out pSize);
+ t_winRtMarshalProxy!.GetMarshalSizeMax(ref riid, pv, dwDestContext, pvDestContext, mshlflags, out pSize);
}
void IMarshal.GetUnmarshalClass(ref Guid riid, IntPtr pv, uint dwDestContext, IntPtr pvDestContext, uint mshlFlags, out Guid pCid)
{
EnsureHasMarshalProxy();
- t_winRtMarshalProxy.GetUnmarshalClass(ref riid, pv, dwDestContext, pvDestContext, mshlFlags, out pCid);
+ t_winRtMarshalProxy!.GetUnmarshalClass(ref riid, pv, dwDestContext, pvDestContext, mshlFlags, out pCid);
}
void IMarshal.MarshalInterface(IntPtr pStm, ref Guid riid, IntPtr pv, uint dwDestContext, IntPtr pvDestContext, uint mshlflags)
{
EnsureHasMarshalProxy();
- t_winRtMarshalProxy.MarshalInterface(pStm, ref riid, pv, dwDestContext, pvDestContext, mshlflags);
+ t_winRtMarshalProxy!.MarshalInterface(pStm, ref riid, pv, dwDestContext, pvDestContext, mshlflags);
}
void IMarshal.ReleaseMarshalData(IntPtr pStm)
{
EnsureHasMarshalProxy();
- t_winRtMarshalProxy.ReleaseMarshalData(pStm);
+ t_winRtMarshalProxy!.ReleaseMarshalData(pStm);
}
void IMarshal.UnmarshalInterface(IntPtr pStm, ref Guid riid, out IntPtr ppv)
{
EnsureHasMarshalProxy();
- t_winRtMarshalProxy.UnmarshalInterface(pStm, ref riid, out ppv);
+ t_winRtMarshalProxy!.UnmarshalInterface(pStm, ref riid, out ppv);
}
#endregion Implementation of IMarshal
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
using System.IO;
using Windows.Foundation;
using Windows.Storage.Streams;
if (destination.Capacity - destinationIndex < count) throw new ArgumentException(SR.Argument_InsufficientSpaceInTargetBuffer);
// If destination is backed by a managed array, use the array instead of the pointer as it does not require pinning:
- byte[] destDataArr;
+ byte[]? destDataArr;
int destDataOffs;
if (destination.TryGetUnderlyingData(out destDataArr, out destDataOffs))
{
if (destination.Length - destinationIndex < count) throw new ArgumentException(SR.Argument_InsufficientArrayElementsAfterOffset);
// If source is backed by a managed array, use the array instead of the pointer as it does not require pinning:
- byte[] srcDataArr;
+ byte[]? srcDataArr;
int srcDataOffs;
if (source.TryGetUnderlyingData(out srcDataArr, out srcDataOffs))
{
if (destination.Capacity - destinationIndex < count) throw new ArgumentException(SR.Argument_InsufficientSpaceInTargetBuffer);
// If source are destination are backed by managed arrays, use the arrays instead of the pointers as it does not require pinning:
- byte[] srcDataArr, destDataArr;
+ byte[]? srcDataArr, destDataArr;
int srcDataOffs, destDataOffs;
bool srcIsManaged = source.TryGetUnderlyingData(out srcDataArr, out srcDataOffs);
Debug.Assert(sourceIndex <= int.MaxValue);
Debug.Assert(destinationIndex <= int.MaxValue);
- Buffer.BlockCopy(srcDataArr, srcDataOffs + (int)sourceIndex, destDataArr, destDataOffs + (int)destinationIndex, (int)count);
+ Buffer.BlockCopy(srcDataArr!, srcDataOffs + (int)sourceIndex, destDataArr!, destDataOffs + (int)destinationIndex, (int)count);
return;
}
Debug.Assert(sourceIndex <= int.MaxValue);
destPtr = destination.GetPointerAtOffset(destinationIndex);
- Marshal.Copy(srcDataArr, srcDataOffs + (int)sourceIndex, destPtr, (int)count);
+ Marshal.Copy(srcDataArr!, srcDataOffs + (int)sourceIndex, destPtr, (int)count);
return;
}
Debug.Assert(destinationIndex <= int.MaxValue);
srcPtr = source.GetPointerAtOffset(sourceIndex);
- Marshal.Copy(srcPtr, destDataArr, destDataOffs + (int)destinationIndex, (int)count);
+ Marshal.Copy(srcPtr, destDataArr!, destDataOffs + (int)destinationIndex, (int)count);
return;
}
/// <param name="underlyingDataArrayStartOffset">Will be set to the start offset of the buffer data in the backing array
/// or to <code>-1</code>.</param>
/// <returns>Whether the <code>IBuffer</code> is backed by a managed byte array.</returns>
- internal static bool TryGetUnderlyingData(this IBuffer buffer, out byte[] underlyingDataArray, out int underlyingDataArrayStartOffset)
+ internal static bool TryGetUnderlyingData(this IBuffer buffer, [NotNullWhen(true)] out byte[]? underlyingDataArray, out int underlyingDataArrayStartOffset)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
- WindowsRuntimeBuffer winRtBuffer = buffer as WindowsRuntimeBuffer;
+ WindowsRuntimeBuffer? winRtBuffer = buffer as WindowsRuntimeBuffer;
if (winRtBuffer == null)
{
underlyingDataArray = null;
/// <returns><code>true</code> if the underlying <code>Buffer</code> memory pointer is the same for both specified
/// <code>IBuffer</code> instances (i.e. if they are backed by the same memory); <code>false</code> otherwise.</returns>
[CLSCompliant(false)]
- public static bool IsSameData(this IBuffer buffer, IBuffer otherBuffer)
+ public static bool IsSameData(this IBuffer buffer, IBuffer? otherBuffer)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
if (buffer == otherBuffer)
return true;
- byte[] thisDataArr, otherDataArr;
+ byte[]? thisDataArr, otherDataArr;
int thisDataOffs, otherDataOffs;
bool thisIsManaged = buffer.TryGetUnderlyingData(out thisDataArr, out thisDataOffs);
{
throw new UnauthorizedAccessException(SR.UnauthorizedAccess_InternalBuffer);
}
- return new WindowsRuntimeBuffer(streamData.Array, (int)streamData.Offset, (int)underlyingStream.Length, underlyingStream.Capacity);
+ return new WindowsRuntimeBuffer(streamData.Array!, (int)streamData.Offset, (int)underlyingStream.Length, underlyingStream.Capacity);
}
int originInStream = streamData.Offset;
int buffCapacity = Math.Min(length, underlyingStream.Capacity - positionInStream);
int buffLength = Math.Max(0, Math.Min(length, ((int)underlyingStream.Length) - positionInStream));
- return new WindowsRuntimeBuffer(streamData.Array, originInStream + positionInStream, buffLength, buffCapacity);
+ return new WindowsRuntimeBuffer(streamData.Array!, originInStream + positionInStream, buffLength, buffCapacity);
}
if (source == null)
throw new ArgumentNullException(nameof(source));
- byte[] dataArr;
+ byte[]? dataArr;
int dataOffs;
if (source.TryGetUnderlyingData(out dataArr, out dataOffs))
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (source.Capacity <= byteOffset) throw new ArgumentException(SR.Argument_BufferIndexExceedsCapacity, nameof(byteOffset));
- byte[] srcDataArr;
+ byte[]? srcDataArr;
int srcDataOffs;
if (source.TryGetUnderlyingData(out srcDataArr, out srcDataOffs))
{
{
if (_ct.CanBeCanceled && !_completing)
{ // benign race on m_completing... it's ok if it's not up-to-date.
- var ctr = _ct.Register(ai => ((IAsyncInfo)ai).Cancel(), asyncInfo); // delegate cached by compiler
+ var ctr = _ct.Register(ai => ((IAsyncInfo)ai!).Cancel(), asyncInfo); // delegate cached by compiler
// The operation may already be completing by this time, in which case
// we might need to dispose of our new cancellation registration here.
/// <param name="asyncInfo">The asynchronous operation.</param>
/// <param name="getResultsFunction">A function used to retrieve the TResult from the async operation; may be null.</param>
/// <param name="asyncStatus">The status of the asynchronous operation.</param>
- private void Complete(IAsyncInfo asyncInfo, Func<IAsyncInfo, TResult> getResultsFunction, AsyncStatus asyncStatus)
+ private void Complete(IAsyncInfo asyncInfo, Func<IAsyncInfo, TResult>? getResultsFunction, AsyncStatus asyncStatus)
{
if (asyncInfo == null)
throw new ArgumentNullException(nameof(asyncInfo));
// Retrieve the completion data from the IAsyncInfo.
TResult result = default(TResult);
- Exception error = null;
+ Exception? error = null;
if (asyncStatus == AsyncStatus.Error)
{
error = asyncInfo.ErrorCode;
case AsyncStatus.Completed:
if (AsyncCausalitySupport.LoggingOn)
AsyncCausalitySupport.TraceOperationCompletedSuccess(this.Task);
- success = base.TrySetResult(result);
+ success = base.TrySetResult(result!);
break;
case AsyncStatus.Error:
{
internal static class ExceptionDispatchHelper
{
- internal static void ThrowAsync(Exception exception, SynchronizationContext targetContext)
+ internal static void ThrowAsync(Exception? exception, SynchronizationContext? targetContext)
{
if (exception == null)
return;
{
try
{
- targetContext.Post((edi) => ((ExceptionDispatchInfo)edi).Throw(), exceptionDispatchInfo);
+ targetContext.Post((edi) => ((ExceptionDispatchInfo)edi!).Throw(), exceptionDispatchInfo);
}
catch
{
bool scheduled = true;
try
{
- new SynchronizationContext().Post((edi) => ((ExceptionDispatchInfo)edi).Throw(), exceptionDispatchInfo);
+ new SynchronizationContext().Post((edi) => ((ExceptionDispatchInfo)edi!).Throw(), exceptionDispatchInfo);
}
catch
{
}
- internal TaskToAsyncActionAdapter(Task underlyingTask, CancellationTokenSource underlyingCancelTokenSource)
+ internal TaskToAsyncActionAdapter(Task underlyingTask, CancellationTokenSource? underlyingCancelTokenSource)
: base(underlyingTask, underlyingCancelTokenSource, underlyingProgressDispatcher: null)
{
using System;
using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
// These two masks are used to clear all STATE_XXXX bits and leave any STATEFLAG_XXXX bits.
private const int STATEMASK_CLEAR_ALL_ASYNC_STATES = ~STATEMASK_SELECT_ANY_ASYNC_STATE;
-
- private static InvalidOperationException CreateCannotGetResultsFromIncompleteOperationException(Exception cause)
+ private static InvalidOperationException CreateCannotGetResultsFromIncompleteOperationException(Exception? cause)
{
InvalidOperationException ex = (cause == null)
? new InvalidOperationException(SR.InvalidOperation_CannotGetResultsFromIncompleteOperation)
#region Instance variables
/// <summary>The token source used to cancel running operations.</summary>
- private CancellationTokenSource _cancelTokenSource = null;
+ private CancellationTokenSource? _cancelTokenSource = null;
/// <summary>The async info's ID. InvalidAsyncId stands for not yet been initialised.</summary>
private uint _id = AsyncInfoIdGenerator.InvalidId;
/// <summary>The cached error code used to avoid creating several exception objects if the <code>ErrorCode</code>
/// property is accessed several times. <code>null</code> indicates either no error or that <code>ErrorCode</code>
/// has not yet been called.</summary>
- private Exception _error = null;
+ private Exception? _error = null;
/// <summary>The state of the async info. Interlocked operations are used to manipulate this field.</summary>
private volatile int _state = STATE_NOT_INITIALIZED;
/// or to one of Task or Task{TResult} in the latter case. This approach allows us to save a field on all IAsyncInfos.
/// Notably, this makes us pay the added cost of boxing for synchronously completing IAsyncInfos where TResult is a
/// value type, however, this is expected to occur rather rare compared to non-synchronously completed user-IAsyncInfos.</summary>
- private object _dataContainer;
+ private object? _dataContainer;
/// <summary>Registered completed handler.</summary>
- private TCompletedHandler _completedHandler;
+ private TCompletedHandler? _completedHandler;
/// <summary>Registered progress handler.</summary>
- private TProgressHandler _progressHandler;
+ private TProgressHandler? _progressHandler;
/// <summary>The synchronization context on which this instance was created/started. Used to callback invocations.</summary>
- private SynchronizationContext _startingContext;
+ private SynchronizationContext? _startingContext;
#endregion Instance variables
// Set the completion routine and let the task running:
task.ContinueWith(
- (_, this_) => ((TaskToAsyncInfoAdapter<TCompletedHandler, TProgressHandler, TResult, TProgressInfo>)this_).TaskCompleted(),
+ (_, this_) => ((TaskToAsyncInfoAdapter<TCompletedHandler, TProgressHandler, TResult, TProgressInfo>)this_!).TaskCompleted(),
this, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
/// <param name="underlyingProgressDispatcher">A progress listener/pugblisher that receives progress notifications
/// form <code>underlyingTask</code>.</param>
internal TaskToAsyncInfoAdapter(Task underlyingTask,
- CancellationTokenSource underlyingCancelTokenSource, Progress<TProgressInfo> underlyingProgressDispatcher)
+ CancellationTokenSource? underlyingCancelTokenSource, Progress<TProgressInfo>? underlyingProgressDispatcher)
{
if (underlyingTask == null)
throw new ArgumentNullException(nameof(underlyingTask));
_state = (STATEFLAG_COMPLETION_HNDL_NOT_YET_INVOKED | STATE_STARTED);
underlyingTask.ContinueWith(
- (_, this_) => ((TaskToAsyncInfoAdapter<TCompletedHandler, TProgressHandler, TResult, TProgressInfo>)this_).TaskCompleted(),
+ (_, this_) => ((TaskToAsyncInfoAdapter<TCompletedHandler, TProgressHandler, TResult, TProgressInfo>)this_!).TaskCompleted(),
this, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
/// specified <code>synchronousResult</code> is used as the result value.
/// </summary>
/// <param name="synchronousResult">The result of this synchronously completed IAsyncInfo.</param>
- internal TaskToAsyncInfoAdapter(TResult synchronousResult)
+ internal TaskToAsyncInfoAdapter([AllowNull] TResult synchronousResult)
{
// We already completed. There will be no progress callback invokations and a potential completed handler invokation will be synchronous.
// We do not need the starting SynchronizationContext:
#region Infrastructure methods
- private SynchronizationContext GetStartingContext()
+ private SynchronizationContext? GetStartingContext()
{
#if DESKTOP // as a reminder that on most platforms we want a different behavior
return SynchronizationContext.CurrentNoFlow;
}
- internal Task Task
+ internal Task? Task
{
get
{
if (CompletedSynchronously)
return null;
- return (Task)_dataContainer;
+ return (Task?)_dataContainer;
}
}
- internal CancellationTokenSource CancelTokenSource
+ internal CancellationTokenSource? CancelTokenSource
{
get { return _cancelTokenSource; }
}
bool conditionFailed;
// Get the handler:
- TCompletedHandler handler = Volatile.Read(ref _completedHandler);
+ TCompletedHandler? handler = Volatile.Read(ref _completedHandler);
// If we might not run the handler now, we need to remember that if it is set later, it will need to be run then:
if (handler == null)
{
var tuple = (Tuple<TaskToAsyncInfoAdapter<TCompletedHandler, TProgressHandler, TResult, TProgressInfo>,
TProgressHandler,
- TProgressInfo>)tupleObject;
+ TProgressInfo>)tupleObject!;
tuple.Item1.OnProgress(tuple.Item2, tuple.Item3);
}, Tuple.Create(this, handler, progressInfo));
void IProgress<TProgressInfo>.Report(TProgressInfo value)
{
// If no progress handler is set, there is nothing to do:
- TProgressHandler handler = Volatile.Read(ref _progressHandler);
+ TProgressHandler? handler = Volatile.Read(ref _progressHandler);
if (handler == null)
return;
}
- private void OnReportChainedProgress(object sender, TProgressInfo progressInfo)
+ private void OnReportChainedProgress(object? sender, TProgressInfo progressInfo)
{
((IProgress<TProgressInfo>)this).Report(progressInfo);
}
Debug.Assert(IsInRunningState);
Debug.Assert(!CompletedSynchronously);
- Task task = _dataContainer as Task;
+ Task? task = _dataContainer as Task;
Debug.Assert(task != null);
Debug.Assert(task.IsCompleted);
// Invoke callback in the right context (delegate cached by compiler):
_startingContext.Post((tupleObject) =>
{
- var tuple = (Tuple<TaskToAsyncInfoAdapter<TCompletedHandler, TProgressHandler, TResult, TProgressInfo>, AsyncStatus>)tupleObject;
+ var tuple = (Tuple<TaskToAsyncInfoAdapter<TCompletedHandler, TProgressHandler, TResult, TProgressInfo>, AsyncStatus>)tupleObject!;
tuple.Item1.OnCompletedInvoker(tuple.Item2);
}, Tuple.Create(this, terminationStatus));
}
return AsyncStatus.Error;
}
-
internal TResult GetResultsInternal()
{
EnsureNotClosed();
// If this IAsyncInfo has actually faulted, GetResults will throw the same error as returned by ErrorCode:
if (IsInErrorState)
{
- Exception error = ErrorCode;
+ Exception? error = ErrorCode;
Debug.Assert(error != null);
ExceptionDispatchInfo.Capture(error).Throw();
}
// If this is a synchronous operation, use the cached result:
if (CompletedSynchronously)
- return (TResult)_dataContainer;
+ return (TResult)_dataContainer!;
// The operation is asynchronous:
- Task<TResult> task = _dataContainer as Task<TResult>;
+ Task<TResult>? task = _dataContainer as Task<TResult>;
// Since CompletedSynchronously is false and EnsureNotClosed() did not throw, task can only be null if:
// - this IAsyncInfo has completed synchronously, however we checked for this above;
// - it was not converted to Task<TResult>, which means it is a non-generic Task. In that case we cannot get a result from Task.
if (task == null)
- return default(TResult);
+ return default(TResult)!;
Debug.Assert(IsInRunToCompletionState);
/// If we the completion handler is set AFTER this IAsyncInfo already completed, then this setter will invoke the handler synchronously
/// on the current context.
/// </summary>
- public virtual TCompletedHandler Completed
+ public virtual TCompletedHandler? Completed
{
get
{
- TCompletedHandler handler = Volatile.Read(ref _completedHandler);
+ TCompletedHandler? handler = Volatile.Read(ref _completedHandler);
EnsureNotClosed();
return handler;
}
// Some other WinRT projection languages do not allow setting the Completed handler more than once, even if it is set to null.
// We could do the same by introducing a new STATEFLAG_COMPLETION_HNDL_SET bit-flag constant and saving a this state into
// the m_state field to indicate that the completion handler has been set previously, but we choose not to do this.)
- TCompletedHandler handlerBefore = Interlocked.CompareExchange(ref _completedHandler, value, null);
+ TCompletedHandler? handlerBefore = Interlocked.CompareExchange(ref _completedHandler, value, null);
if (handlerBefore != null)
{
InvalidOperationException ex = new InvalidOperationException(SR.InvalidOperation_CannotSetCompletionHanlderMoreThanOnce);
/// <summary>Gets or sets the progress handler.</summary>
- public virtual TProgressHandler Progress
+ public virtual TProgressHandler? Progress
{
get
{
- TProgressHandler handler = Volatile.Read(ref _progressHandler);
+ TProgressHandler? handler = Volatile.Read(ref _progressHandler);
EnsureNotClosed();
return handler;
/// <summary>Gets the error code for the async info.</summary>
- public virtual Exception ErrorCode
+ public virtual Exception? ErrorCode
{
get
{
if (!IsInErrorState)
return null;
- Exception error = Volatile.Read(ref _error);
+ Exception? error = Volatile.Read(ref _error);
// ERROR is a terminal state. SO if we have an error, just return it.
// If we completed synchronously, we return the current error iven if it is null since we do not expect this to change:
if (error != null || CompletedSynchronously)
return error;
- Task task = _dataContainer as Task;
+ Task? task = _dataContainer as Task;
Debug.Assert(task != null);
- AggregateException aggregateException = task.Exception;
+ AggregateException? aggregateException = task.Exception;
// By spec, if task.IsFaulted is true, then task.Exception must not be null and its InnerException must
// also not be null. However, in case something is unexpected on the Task side of the road, let?s be defensive
}
else
{
- Exception innerException = aggregateException.InnerException;
+ Exception? innerException = aggregateException.InnerException;
error = (innerException == null)
? aggregateException
// If m_error was set concurrently, setError will be non-null. Then we use that - as it is the first m_error
// that was set. If setError we know that we won any races and we can return error:
- Exception setError = Interlocked.CompareExchange(ref _error, error, null);
+ Exception? setError = Interlocked.CompareExchange(ref _error, error, null);
return setError ?? error;
}
}
using System;
using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using Windows.Foundation;
}
- internal TaskToAsyncOperationAdapter(Task underlyingTask, CancellationTokenSource underlyingCancelTokenSource)
+ internal TaskToAsyncOperationAdapter(Task underlyingTask, CancellationTokenSource? underlyingCancelTokenSource)
: base(underlyingTask, underlyingCancelTokenSource, underlyingProgressDispatcher: null)
{
}
- internal TaskToAsyncOperationAdapter(TResult synchronousResult)
+ internal TaskToAsyncOperationAdapter([AllowNull] TResult synchronousResult)
: base(synchronousResult)
{
}
-
public virtual TResult GetResults()
{
return GetResultsInternal();
using System;
using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using Windows.Foundation;
//}
- internal TaskToAsyncOperationWithProgressAdapter(TResult synchronousResult)
+ internal TaskToAsyncOperationWithProgressAdapter([AllowNull] TResult synchronousResult)
: base(synchronousResult)
{
}
-
public virtual TResult GetResults()
{
return GetResultsInternal();
_dispatcher = dispatcher;
}
- public override void Post(SendOrPostCallback d, object state)
+ public override void Post(SendOrPostCallback d, object? state)
{
if (d == null)
throw new ArgumentNullException(nameof(d));
_dispatcherQueue = dispatcherQueue;
}
- public override void Post(SendOrPostCallback d, object state)
+ public override void Post(SendOrPostCallback d, object? state)
{
if (d == null)
throw new ArgumentNullException(nameof(d));
protected class Invoker
{
- private readonly ExecutionContext _executionContext;
+ private readonly ExecutionContext? _executionContext;
private readonly SendOrPostCallback _callback;
- private readonly object _state;
+ private readonly object? _state;
private static readonly ContextCallback s_contextCallback = new ContextCallback(InvokeInContext);
- public Invoker(SendOrPostCallback callback, object state)
+ public Invoker(SendOrPostCallback callback, object? state)
{
_executionContext = ExecutionContext.Capture();
_callback = callback;
ExecutionContext.Run(_executionContext, s_contextCallback, this);
}
- private static void InvokeInContext(object thisObj)
+ private static void InvokeInContext(object? thisObj)
{
- ((Invoker)thisObj).InvokeCore();
+ ((Invoker)thisObj!).InvokeCore();
}
private void InvokeCore()
if (!ExceptionSupport.ReportUnhandledError(ex))
{
var edi = ExceptionDispatchInfo.Capture(ex);
- ThreadPool.QueueUserWorkItem(o => ((ExceptionDispatchInfo)o).Throw(), edi);
+ ThreadPool.QueueUserWorkItem(o => ((ExceptionDispatchInfo)o!).Throw(), edi);
}
}
}
#endregion class WinRTSynchronizationContext.Invoker
- public override void Send(SendOrPostCallback d, object state)
+ public override void Send(SendOrPostCallback d, object? state)
{
throw new NotSupportedException(SR.InvalidOperation_SendNotSupportedOnWindowsRTSynchronizationContext);
}
return ConvertToString(null /* format string */, null /* format provider */);
}
- public string ToString(IFormatProvider provider)
+ public string ToString(IFormatProvider? provider)
{
// Delegate to the internal method which implements all ToString calls.
return ConvertToString(null /* format string */, provider);
}
- string IFormattable.ToString(string format, IFormatProvider provider)
+ string IFormattable.ToString(string? format, IFormatProvider? provider)
{
// Delegate to the internal method which implements all ToString calls.
return ConvertToString(format, provider);
}
- private string ConvertToString(string format, IFormatProvider provider)
+ private string ConvertToString(string? format, IFormatProvider? provider)
{
// Helper to get the numeric list separator for a given culture.
char separator = TokenizerHelper.GetNumericListSeparator(provider);
return !(point1 == point2);
}
- public override bool Equals(object o)
+ public override bool Equals(object? o)
{
return o is Point && this == (Point)o;
}
return ConvertToString(null /* format string */, null /* format provider */);
}
- public string ToString(IFormatProvider provider)
+ public string ToString(IFormatProvider? provider)
{
// Delegate to the internal method which implements all ToString calls.
return ConvertToString(null /* format string */, provider);
}
- string IFormattable.ToString(string format, IFormatProvider provider)
+ string IFormattable.ToString(string? format, IFormatProvider? provider)
{
// Delegate to the internal method which implements all ToString calls.
return ConvertToString(format, provider);
}
- internal string ConvertToString(string format, IFormatProvider provider)
+ internal string ConvertToString(string? format, IFormatProvider? provider)
{
if (IsEmpty)
{
return !(rect1 == rect2);
}
- public override bool Equals(object o)
+ public override bool Equals(object? o)
{
return o is Rect && this == (Rect)o;
}
return !(size1 == size2);
}
- public override bool Equals(object o)
+ public override bool Equals(object? o)
{
return o is Size && Size.Equals(this, (Size)o);
}
internal static class TokenizerHelper
{
- internal static char GetNumericListSeparator(IFormatProvider provider)
+ internal static char GetNumericListSeparator(IFormatProvider? provider)
{
char numericSeparator = ',';
return ConvertToString(null, null);
}
- public string ToString(IFormatProvider provider)
+ public string ToString(IFormatProvider? provider)
{
// Delegate to the internal method which implements all ToString calls.
return ConvertToString(null, provider);
}
- string IFormattable.ToString(string format, IFormatProvider provider)
+ string IFormattable.ToString(string? format, IFormatProvider? provider)
{
// Delegate to the internal method which implements all ToString calls.
return ConvertToString(format, provider);
}
- internal string ConvertToString(string format, IFormatProvider provider)
+ internal string ConvertToString(string? format, IFormatProvider? provider)
{
StringBuilder sb = new StringBuilder();
return _A.GetHashCode() ^ _R.GetHashCode() ^ _G.GetHashCode() ^ _B.GetHashCode();
}
- public override bool Equals(object o)
+ public override bool Equals(object? o)
{
return o is Color && this == (Color)o;
}
{
Debug.Assert(sink != null);
- CancellationTokenRegistration ctReg = source.Register((state) => { ((CancellationTokenSource)state).Cancel(); },
+ CancellationTokenRegistration ctReg = source.Register((state) => { ((CancellationTokenSource)state!).Cancel(); },
sink);
- concatenationLifetime.ContinueWith((_, state) => { ((CancellationTokenRegistration)state).Dispose(); },
+ concatenationLifetime.ContinueWith((_, state) => { ((CancellationTokenRegistration)state!).Dispose(); },
ctReg, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
var wrapper = source as TaskToAsyncActionAdapter;
if (wrapper != null && !wrapper.CompletedSynchronously)
{
- Task innerTask = wrapper.Task;
+ Task? innerTask = wrapper.Task;
Debug.Assert(innerTask != null);
Debug.Assert(innerTask.Status != TaskStatus.Created);
var wrapper = source as TaskToAsyncOperationAdapter<TResult>;
if (wrapper != null && !wrapper.CompletedSynchronously)
{
- Task<TResult> innerTask = wrapper.Task as Task<TResult>;
+ Task<TResult>? innerTask = wrapper.Task as Task<TResult>;
Debug.Assert(innerTask != null);
Debug.Assert(innerTask.Status != TaskStatus.Created); // Is WaitingForActivation a legal state at this moment?
/// <param name="source">The asynchronous operation.</param>
/// <param name="progress">The progress object used to receive progress updates.</param>
/// <returns>The Task representing the asynchronous operation.</returns>
- public static Task AsTask<TProgress>(this IAsyncActionWithProgress<TProgress> source, IProgress<TProgress> progress)
+ public static Task AsTask<TProgress>(this IAsyncActionWithProgress<TProgress> source, IProgress<TProgress>? progress)
{
return AsTask(source, CancellationToken.None, progress);
}
/// <param name="progress">The progress object used to receive progress updates.</param>
/// <returns>The Task representing the asynchronous operation.</returns>
public static Task AsTask<TProgress>(this IAsyncActionWithProgress<TProgress> source,
- CancellationToken cancellationToken, IProgress<TProgress> progress)
+ CancellationToken cancellationToken, IProgress<TProgress>? progress)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
var wrapper = source as TaskToAsyncActionWithProgressAdapter<TProgress>;
if (wrapper != null && !wrapper.CompletedSynchronously)
{
- Task innerTask = wrapper.Task;
+ Task? innerTask = wrapper.Task;
Debug.Assert(innerTask != null);
Debug.Assert(innerTask.Status != TaskStatus.Created); // Is WaitingForActivation a legal state at this moment?
/// <param name="progress">The progress object used to receive progress updates.</param>
/// <returns>The Task representing the asynchronous operation.</returns>
public static Task<TResult> AsTask<TResult, TProgress>(this IAsyncOperationWithProgress<TResult, TProgress> source,
- IProgress<TProgress> progress)
+ IProgress<TProgress>? progress)
{
return AsTask(source, CancellationToken.None, progress);
}
/// <param name="progress">The progress object used to receive progress updates.</param>
/// <returns>The Task representing the asynchronous operation.</returns>
public static Task<TResult> AsTask<TResult, TProgress>(this IAsyncOperationWithProgress<TResult, TProgress> source,
- CancellationToken cancellationToken, IProgress<TProgress> progress)
+ CancellationToken cancellationToken, IProgress<TProgress>? progress)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
var wrapper = source as TaskToAsyncOperationWithProgressAdapter<TResult, TProgress>;
if (wrapper != null && !wrapper.CompletedSynchronously)
{
- Task<TResult> innerTask = wrapper.Task as Task<TResult>;
+ Task<TResult>? innerTask = wrapper.Task as Task<TResult>;
Debug.Assert(innerTask != null);
Debug.Assert(innerTask.Status != TaskStatus.Created); // Is WaitingForActivation a legal state at this moment?
{
// This method is an aid for NGen to save common generic
// instantiations into the ngen image.
- ((IAsyncOperation<bool>)null).AsTask();
- ((IAsyncOperation<string>)null).AsTask();
- ((IAsyncOperation<object>)null).AsTask();
- ((IAsyncOperation<uint>)null).AsTask();
-
- ((IAsyncOperationWithProgress<uint, uint>)null).AsTask();
- ((IAsyncOperationWithProgress<ulong, ulong>)null).AsTask();
- ((IAsyncOperationWithProgress<string, ulong>)null).AsTask();
+ ((IAsyncOperation<bool>)null!).AsTask();
+ ((IAsyncOperation<string>)null!).AsTask();
+ ((IAsyncOperation<object>)null!).AsTask();
+ ((IAsyncOperation<uint>)null!).AsTask();
+
+ ((IAsyncOperationWithProgress<uint, uint>)null!).AsTask();
+ ((IAsyncOperationWithProgress<ulong, ulong>)null!).AsTask();
+ ((IAsyncOperationWithProgress<string, ulong>)null!).AsTask();
}
} // class WindowsRuntimeSystemExtensions
} // namespace
{
public abstract bool Initialize(string libpath, string reswFilename, out PRIExceptionInfo? exceptionInfo);
- public abstract string GetString(string stringName, string? startingCulture, string? neutralResourcesCulture);
+ public abstract string? GetString(string stringName, string? startingCulture, string? neutralResourcesCulture);
public abstract CultureInfo? GlobalResourceContextBestFitCultureInfo
{
// See the LICENSE file in the project root for more information.
using System;
+using System.Diagnostics.CodeAnalysis;
namespace Internal.Runtime.InteropServices.WindowsRuntime
{
/// Attach restricted error information to the exception if it may apply to that exception, returning
/// back the input value
/// </summary>
+ [return: NotNullIfNotNull("e")]
public static Exception? AttachRestrictedErrorInfo(Exception? e) => throw new PlatformNotSupportedException();
/// <summary>