* All AsyncResult classes have nullable enable.
* Most ancillary files annotated.
* UdpClient annotated
* Annotate TcpClient
* Annotate TcpListener, SafeSocketHandle, SocketTaskExtensions
* Annotate NetworkStream and SendPacketsElement
* Annotate SocketPal.
* Annotate SocketAsyncEventArgs
* Annotate SocketAsyncEngine and Context on Unix
* Annotate Socket.Tasks
* Finish annotating the Socket class.
* Remove inline #nullable lines
* Annotate all public methods.
* Sync up to latest code and cleanup.
* Fix .NET Framework build for WinHttpHandler.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System;
using System.Net.Sockets;
using System.Runtime.InteropServices;
[DllImport(Interop.Libraries.Mswsock, SetLastError = true)]
internal static extern unsafe bool TransmitFile(
SafeHandle socket,
- SafeHandle fileHandle,
+ SafeHandle? fileHandle,
int numberOfBytesToWrite,
int numberOfBytesPerSend,
NativeOverlapped* overlapped,
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System;
using System.Net.Sockets;
using System.Runtime.InteropServices;
internal static extern SocketError WSAIoctl_Blocking(
SafeSocketHandle socketHandle,
[In] int ioControlCode,
- [In] byte[] inBuffer,
+ [In] byte[]? inBuffer,
[In] int inBufferSize,
- [Out] byte[] outBuffer,
+ [Out] byte[]? outBuffer,
[In] int outBufferSize,
[Out] out int bytesTransferred,
[In] IntPtr overlapped,
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System;
using System.Net.Sockets;
using System.Runtime.InteropServices;
[In] SafeSocketHandle socketHandle,
[In] SocketOptionLevel optionLevel,
[In] SocketOptionName optionName,
- [In] byte[] optionValue,
+ [In] byte[]? optionValue,
[In] int optionLength);
[DllImport(Interop.Libraries.Ws2_32, SetLastError = true)]
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
{
internal sealed class SafeNativeOverlapped : SafeHandle
{
- private readonly SafeSocketHandle _socketHandle;
+ private readonly SafeSocketHandle? _socketHandle;
private SafeNativeOverlapped()
: this(IntPtr.Zero)
{
Debug.Assert(_socketHandle != null, "_socketHandle is null.");
- ThreadPoolBoundHandle boundHandle = _socketHandle.IOCPBoundHandle;
+ ThreadPoolBoundHandle? boundHandle = _socketHandle.IOCPBoundHandle;
Debug.Assert(boundHandle != null, "SafeNativeOverlapped::FreeNativeOverlapped - boundHandle is null");
// FreeNativeOverlapped will be called even if boundHandle was previously disposed.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System.Security.Principal;
namespace System.Net
{
internal partial class ContextAwareResult
{
- private WindowsIdentity _windowsIdentity;
+ private WindowsIdentity? _windowsIdentity;
// Security: We need an assert for a call into WindowsIdentity.GetCurrent.
private void SafeCaptureIdentity()
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System.Threading;
namespace System.Net
// to have several pending IOs differentiated by their state object. We don't want that pattern to break the cache.
internal class CallbackClosure
{
- private readonly AsyncCallback _savedCallback;
- private readonly ExecutionContext _savedContext;
+ private readonly AsyncCallback? _savedCallback;
+ private readonly ExecutionContext? _savedContext;
internal CallbackClosure(ExecutionContext context, AsyncCallback callback)
{
}
}
- internal bool IsCompatible(AsyncCallback callback)
+ internal bool IsCompatible(AsyncCallback? callback)
{
if (callback == null || _savedCallback == null)
{
return true;
}
- internal AsyncCallback AsyncCallback
+ internal AsyncCallback? AsyncCallback
{
get
{
}
}
- internal ExecutionContext Context
+ internal ExecutionContext? Context
{
get
{
}
// This needs to be volatile so it's sure to make it over to the completion thread in time.
- private volatile ExecutionContext _context;
- private object _lock;
+ private volatile ExecutionContext? _context;
+ private object? _lock;
private StateFlags _flags;
- internal ContextAwareResult(object myObject, object myState, AsyncCallback myCallBack) :
+ internal ContextAwareResult(object myObject, object? myState, AsyncCallback? myCallBack) :
this(false, false, myObject, myState, myCallBack)
{ }
//
// Setting forceCaptureContext enables the ContextCopy property even when a null callback is specified. (The context is
// always captured if a callback is given.)
- internal ContextAwareResult(bool captureIdentity, bool forceCaptureContext, object myObject, object myState, AsyncCallback myCallBack) :
+ internal ContextAwareResult(bool captureIdentity, bool forceCaptureContext, object myObject, object? myState, AsyncCallback? myCallBack) :
this(captureIdentity, forceCaptureContext, false, myObject, myState, myCallBack)
{ }
- internal ContextAwareResult(bool captureIdentity, bool forceCaptureContext, bool threadSafeContextCopy, object myObject, object myState, AsyncCallback myCallBack) :
+ internal ContextAwareResult(bool captureIdentity, bool forceCaptureContext, bool threadSafeContextCopy, object myObject, object? myState, AsyncCallback? myCallBack) :
base(myObject, myState, myCallBack)
{
if (forceCaptureContext)
// May block briefly if the context is still being produced.
//
// Returns null if called from the posting thread.
- internal ExecutionContext ContextCopy
+ internal ExecutionContext? ContextCopy
{
get
{
throw new InvalidOperationException(SR.net_completed_result);
}
- ExecutionContext context = _context;
+ ExecutionContext? context = _context;
if (context != null)
{
return context; // No need to copy on CoreCLR; ExecutionContext is immutable
internal object StartPostingAsyncOp()
{
- return StartPostingAsyncOp(true);
+ return StartPostingAsyncOp(true)!;
}
// If ContextCopy or Identity will be used, the return value should be locked until FinishPostingAsyncOp() is called
// or the operation has been aborted (e.g. by BeginXxx throwing). Otherwise, this can be called with false to prevent the lock
// object from being created.
- internal object StartPostingAsyncOp(bool lockCapture)
+ internal object? StartPostingAsyncOp(bool lockCapture)
{
if (InternalPeekCompleted)
{
_flags |= StateFlags.PostBlockFinished;
- ExecutionContext cachedContext = null;
+ ExecutionContext? cachedContext = null;
return CaptureOrComplete(ref cachedContext, false);
}
// Call this when returning control to the user. Allows a cached Callback Closure to be supplied and used
// as appropriate, and replaced with a new one.
- internal bool FinishPostingAsyncOp(ref CallbackClosure closure)
+ internal bool FinishPostingAsyncOp(ref CallbackClosure? closure)
{
// Ignore this call if StartPostingAsyncOp() failed or wasn't called, or this has already been called.
if ((_flags & (StateFlags.PostBlockStarted | StateFlags.PostBlockFinished)) != StateFlags.PostBlockStarted)
_flags |= StateFlags.PostBlockFinished;
// Need a copy of this ref argument since it can be used in many of these calls simultaneously.
- CallbackClosure closureCopy = closure;
- ExecutionContext cachedContext;
+ CallbackClosure? closureCopy = closure;
+ ExecutionContext? cachedContext;
if (closureCopy == null)
{
cachedContext = null;
// called.
//
// Returns whether the operation completed sync or not.
- private bool CaptureOrComplete(ref ExecutionContext cachedContext, bool returnContext)
+ private bool CaptureOrComplete(ref ExecutionContext? cachedContext, bool returnContext)
{
if ((_flags & StateFlags.PostBlockStarted) == 0)
{
return;
}
- ExecutionContext context = _context;
+ ExecutionContext? context = _context;
// If the context is being abandoned or wasn't captured (SuppressFlow, null AsyncCallback), just
// complete regularly, as long as CaptureOrComplete() has finished.
return;
}
- ExecutionContext.Run(context, s => ((ContextAwareResult)s).CompleteCallback(), this);
+ ExecutionContext.Run(context, s => ((ContextAwareResult)s!).CompleteCallback(), this);
}
private void CompleteCallback()
base.Complete(IntPtr.Zero);
}
- internal virtual EndPoint RemoteEndPoint => null;
+ internal virtual EndPoint? RemoteEndPoint => null;
}
}
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using Microsoft.Win32.SafeHandles;
namespace System.Net
//
internal abstract class DebugSafeHandleMinusOneIsInvalid : SafeHandleMinusOneIsInvalid
{
- private string _trace;
+ private string _trace = null!; // initialized by helper called from ctor
protected DebugSafeHandleMinusOneIsInvalid(bool ownsHandle) : base(ownsHandle)
{
{
private readonly EndPoint? _endPoint;
- public ExtendedSocketException(int errorCode, EndPoint endPoint)
+ public ExtendedSocketException(int errorCode, EndPoint? endPoint)
: base(errorCode)
{
_endPoint = endPoint;
(_endPoint == null) ? base.Message : base.Message + " " + _endPoint.ToString();
}
- public static SocketException CreateSocketException(int socketError, EndPoint endPoint)
+ public static SocketException CreateSocketException(int socketError, EndPoint? endPoint)
{
return new ExtendedSocketException(socketError, endPoint);
}
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
// This is to avoid user mistakes when they queue another async op from a callback the completes sync.
[ThreadStatic]
- private static ThreadContext t_threadContext;
+ private static ThreadContext? t_threadContext;
private static ThreadContext CurrentThreadContext
{
get
{
- ThreadContext threadContext = t_threadContext;
+ ThreadContext? threadContext = t_threadContext;
if (threadContext == null)
{
threadContext = new ThreadContext();
}
#if DEBUG
- internal object _debugAsyncChain = null; // Optionally used to track chains of async calls.
+ internal object? _debugAsyncChain = null; // Optionally used to track chains of async calls.
private bool _protectState; // Used by ContextAwareResult to prevent some calls.
#endif
private readonly object _asyncObject; // Caller's async object.
- private readonly object _asyncState; // Caller's state object.
- private AsyncCallback _asyncCallback; // Caller's callback method.
- private object _result; // Final IO result to be returned byt the End*() method.
+ private readonly object? _asyncState; // Caller's state object.
+ private AsyncCallback? _asyncCallback; // Caller's callback method.
+ private object? _result; // Final IO result to be returned byt the End*() method.
private int _errorCode; // Win32 error code for Win32 IO async calls (that want to throw).
private int _intCompleted; // Sign bit indicates synchronous completion if set.
// Remaining bits count the number of InvokeCallbak() calls.
private bool _endCalled; // True if the user called the End*() method.
private bool _userEvent; // True if the event has been (or is about to be) handed to the user
- private object _event; // Lazy allocated event to be returned in the IAsyncResult for the client to wait on.
+ private object? _event; // Lazy allocated event to be returned in the IAsyncResult for the client to wait on.
- internal LazyAsyncResult(object myObject, object myState, AsyncCallback myCallBack)
+ internal LazyAsyncResult(object myObject, object? myState, AsyncCallback? myCallBack)
{
_asyncObject = myObject;
_asyncState = myState;
}
// Interface method to return the caller's state object.
- public object AsyncState
+ public object? AsyncState
{
get
{
}
}
- protected AsyncCallback AsyncCallback
+ protected AsyncCallback? AsyncCallback
{
get
{
}
#endif
- ManualResetEvent asyncEvent;
-
// Indicates that the user has seen the event; it can't be disposed.
_userEvent = true;
// possible for _event to become null immediately after being set, but only if
// IsCompleted has become true. Therefore it's possible for this property
// to give different (set) events to different callers when IsCompleted is true.
- asyncEvent = (ManualResetEvent)_event;
+ ManualResetEvent? asyncEvent = (ManualResetEvent?)_event;
while (asyncEvent == null)
{
LazilyCreateEvent(out asyncEvent);
}
// Internal property for setting the IO result.
- internal object Result
+ internal object? Result
{
get
{
// Used by derived classes to pass context into an overridden Complete(). Useful
// for determining the 'winning' thread in case several may simultaneously call
// the equivalent of InvokeCallback().
- protected void ProtectedInvokeCallback(object result, IntPtr userToken)
+ protected void ProtectedInvokeCallback(object? result, IntPtr userToken)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, result, userToken);
_result = result;
}
- ManualResetEvent asyncEvent = (ManualResetEvent)_event;
+ ManualResetEvent? asyncEvent = (ManualResetEvent?)_event;
if (asyncEvent != null)
{
try
}
// Completes the IO with a result and invoking the user's callback.
- internal void InvokeCallback(object result)
+ internal void InvokeCallback(object? result)
{
ProtectedInvokeCallback(result, IntPtr.Zero);
}
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "*** OFFLOADED the user callback ****");
Task.Factory.StartNew(
- s => WorkerThreadComplete(s),
+ s => WorkerThreadComplete(s!),
this,
CancellationToken.None,
TaskCreationOptions.DenyChildAttach,
try
{
- thisPtr._asyncCallback(thisPtr);
+ thisPtr._asyncCallback!(thisPtr);
}
finally
{
{
}
- internal object InternalWaitForCompletion()
+ internal object? InternalWaitForCompletion()
{
return WaitForCompletion(true);
}
- private object WaitForCompletion(bool snap)
+ private object? WaitForCompletion(bool snap)
{
- ManualResetEvent waitHandle = null;
+ ManualResetEvent? waitHandle = null;
bool createdByMe = false;
bool complete = snap ? IsCompleted : InternalPeekCompleted;
if (!complete)
{
// Not done yet, so wait:
- waitHandle = (ManualResetEvent)_event;
+ waitHandle = (ManualResetEvent?)_event;
if (waitHandle == null)
{
createdByMe = LazilyCreateEvent(out waitHandle);
{
// Does _userEvent need to be volatile (or _event set via Interlocked) in order
// to avoid giving a user a disposed event?
- ManualResetEvent oldEvent = (ManualResetEvent)_event;
+ ManualResetEvent? oldEvent = (ManualResetEvent?)_event;
_event = null;
if (!_userEvent)
{
- oldEvent.Dispose();
+ oldEvent?.Dispose();
}
}
}
#nullable enable
using System.Collections;
using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Tracing;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
/// <param name="arg1">The second object to log.</param>
/// <param name="memberName">The calling member.</param>
[NonEvent]
- public static void Enter(object? thisOrContextObject, object arg0, object arg1, [CallerMemberName] string? memberName = null)
+ public static void Enter(object? thisOrContextObject, object? arg0, object arg1, [CallerMemberName] string? memberName = null)
{
DebugValidateArg(thisOrContextObject);
DebugValidateArg(arg0);
/// <param name="arg0">A return value from the member.</param>
/// <param name="memberName">The calling member.</param>
[NonEvent]
- public static void Exit(object? thisOrContextObject, object arg0, [CallerMemberName] string? memberName = null)
+ public static void Exit(object? thisOrContextObject, object? arg0, [CallerMemberName] string? memberName = null)
{
DebugValidateArg(thisOrContextObject);
DebugValidateArg(arg0);
/// <param name="formattableString">The message to be logged.</param>
/// <param name="memberName">The calling member.</param>
[NonEvent]
+#if NETCOREAPP
+ [DoesNotReturn]
+#endif
public static void Fail(object? thisOrContextObject, FormattableString formattableString, [CallerMemberName] string? memberName = null)
{
// Don't call DebugValidateArg on args, as we expect Fail to be used in assert/failure situations
/// <param name="message">The message to be logged.</param>
/// <param name="memberName">The calling member.</param>
[NonEvent]
+#if NETCOREAPP
+ [DoesNotReturn]
+#endif
public static void Fail(object? thisOrContextObject, object message, [CallerMemberName] string? memberName = null)
{
// Don't call DebugValidateArg on args, as we expect Fail to be used in assert/failure situations
SafePipeHandle? clientHandle = null;
try
{
- socket.Connect(new UnixDomainSocketEndPoint(_normalizedPipePath));
+ socket.Connect(new UnixDomainSocketEndPoint(_normalizedPipePath!));
clientHandle = new SafePipeHandle(socket);
ConfigureSocket(socket, clientHandle, _direction, 0, 0, _inheritability);
}
try
{
- return await InternalHandle!.NamedPipeSocket.ReceiveAsync(destination, SocketFlags.None, cancellationToken).ConfigureAwait(false);
+ return await InternalHandle!.NamedPipeSocket!.ReceiveAsync(destination, SocketFlags.None, cancellationToken).ConfigureAwait(false);
}
catch (SocketException e)
{
{
while (source.Length > 0)
{
- int bytesWritten = await _handle!.NamedPipeSocket.SendAsync(source, SocketFlags.None, cancellationToken).ConfigureAwait(false);
+ int bytesWritten = await _handle!.NamedPipeSocket!.SendAsync(source, SocketFlags.None, cancellationToken).ConfigureAwait(false);
Debug.Assert(bytesWritten > 0 && bytesWritten <= source.Length);
source = source.Slice(bytesWritten);
}
private int _dummyPrimitive;
public System.Net.IPAddress Address { get { throw null; } }
public int Interface { get { throw null; } }
- public override bool Equals(object comparand) { throw null; }
+ public override bool Equals(object? comparand) { throw null; }
public override int GetHashCode() { throw null; }
public static bool operator ==(System.Net.Sockets.IPPacketInformation packetInformation1, System.Net.Sockets.IPPacketInformation packetInformation2) { throw null; }
public static bool operator !=(System.Net.Sockets.IPPacketInformation packetInformation1, System.Net.Sockets.IPPacketInformation packetInformation2) { throw null; }
public MulticastOption(System.Net.IPAddress group, System.Net.IPAddress mcint) { }
public System.Net.IPAddress Group { get { throw null; } set { } }
public int InterfaceIndex { get { throw null; } set { } }
- public System.Net.IPAddress LocalAddress { get { throw null; } set { } }
+ public System.Net.IPAddress? LocalAddress { get { throw null; } set { } }
}
public partial class NetworkStream : System.IO.Stream
{
public System.Net.Sockets.Socket Socket { get { throw null; } }
protected bool Writeable { get { throw null; } set { } }
public override int WriteTimeout { get { throw null; } set { } }
- public override System.IAsyncResult BeginRead(byte[] buffer, int offset, int size, System.AsyncCallback callback, object state) { throw null; }
- public override System.IAsyncResult BeginWrite(byte[] buffer, int offset, int size, System.AsyncCallback callback, object state) { throw null; }
+ public override System.IAsyncResult BeginRead(byte[] buffer, int offset, int size, System.AsyncCallback? callback, object? state) { throw null; }
+ public override System.IAsyncResult BeginWrite(byte[] buffer, int offset, int size, System.AsyncCallback? callback, object? state) { throw null; }
public void Close(int timeout) { }
protected override void Dispose(bool disposing) { }
public override int EndRead(System.IAsyncResult asyncResult) { throw null; }
public SendPacketsElement(string filepath, int offset, int count, bool endOfPacket) { }
public SendPacketsElement(string filepath, long offset, int count) { }
public SendPacketsElement(string filepath, long offset, int count, bool endOfPacket) { }
- public byte[] Buffer { get { throw null; } }
+ public byte[]? Buffer { get { throw null; } }
public int Count { get { throw null; } }
public bool EndOfPacket { get { throw null; } }
- public string FilePath { get { throw null; } }
- public System.IO.FileStream FileStream { get { throw null; } }
+ public string? FilePath { get { throw null; } }
+ public System.IO.FileStream? FileStream { get { throw null; } }
public int Offset { get { throw null; } }
public long OffsetLong { get { throw null; } }
}
public bool ExclusiveAddressUse { get { throw null; } set { } }
public System.IntPtr Handle { get { throw null; } }
public bool IsBound { get { throw null; } }
- public System.Net.Sockets.LingerOption LingerState { get { throw null; } set { } }
- public System.Net.EndPoint LocalEndPoint { get { throw null; } }
+ [System.Diagnostics.CodeAnalysis.DisallowNullAttribute]
+ public System.Net.Sockets.LingerOption? LingerState { get { throw null; } set { } }
+ public System.Net.EndPoint? LocalEndPoint { get { throw null; } }
public bool MulticastLoopback { get { throw null; } set { } }
public bool NoDelay { get { throw null; } set { } }
public static bool OSSupportsIPv4 { get { throw null; } }
public System.Net.Sockets.ProtocolType ProtocolType { get { throw null; } }
public int ReceiveBufferSize { get { throw null; } set { } }
public int ReceiveTimeout { get { throw null; } set { } }
- public System.Net.EndPoint RemoteEndPoint { get { throw null; } }
+ public System.Net.EndPoint? RemoteEndPoint { get { throw null; } }
public System.Net.Sockets.SafeSocketHandle SafeHandle { get { throw null; } }
public int SendBufferSize { get { throw null; } set { } }
public int SendTimeout { get { throw null; } set { } }
public bool UseOnlyOverlappedIO { get { throw null; } set { } }
public System.Net.Sockets.Socket Accept() { throw null; }
public bool AcceptAsync(System.Net.Sockets.SocketAsyncEventArgs e) { throw null; }
- public System.IAsyncResult BeginAccept(System.AsyncCallback callback, object state) { throw null; }
- public System.IAsyncResult BeginAccept(int receiveSize, System.AsyncCallback callback, object state) { throw null; }
- public System.IAsyncResult BeginAccept(System.Net.Sockets.Socket acceptSocket, int receiveSize, System.AsyncCallback callback, object state) { throw null; }
- public System.IAsyncResult BeginConnect(System.Net.EndPoint remoteEP, System.AsyncCallback callback, object state) { throw null; }
- public System.IAsyncResult BeginConnect(System.Net.IPAddress address, int port, System.AsyncCallback requestCallback, object state) { throw null; }
- public System.IAsyncResult BeginConnect(System.Net.IPAddress[] addresses, int port, System.AsyncCallback requestCallback, object state) { throw null; }
- public System.IAsyncResult BeginConnect(string host, int port, System.AsyncCallback requestCallback, object state) { throw null; }
- public System.IAsyncResult BeginDisconnect(bool reuseSocket, System.AsyncCallback callback, object state) { throw null; }
- public System.IAsyncResult BeginReceive(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, System.AsyncCallback callback, object state) { throw null; }
- public System.IAsyncResult BeginReceive(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode, System.AsyncCallback callback, object state) { throw null; }
- public System.IAsyncResult BeginReceive(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags, System.AsyncCallback callback, object state) { throw null; }
- public System.IAsyncResult BeginReceive(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode, System.AsyncCallback callback, object state) { throw null; }
- public System.IAsyncResult BeginReceiveFrom(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, ref System.Net.EndPoint remoteEP, System.AsyncCallback callback, object state) { throw null; }
- public System.IAsyncResult BeginReceiveMessageFrom(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, ref System.Net.EndPoint remoteEP, System.AsyncCallback callback, object state) { throw null; }
- public System.IAsyncResult BeginSend(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, System.AsyncCallback callback, object state) { throw null; }
- public System.IAsyncResult BeginSend(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode, System.AsyncCallback callback, object state) { throw null; }
- public System.IAsyncResult BeginSend(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags, System.AsyncCallback callback, object state) { throw null; }
- public System.IAsyncResult BeginSend(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode, System.AsyncCallback callback, object state) { throw null; }
- public System.IAsyncResult BeginSendFile(string fileName, System.AsyncCallback callback, object state) { throw null; }
- public System.IAsyncResult BeginSendFile(string fileName, byte[] preBuffer, byte[] postBuffer, System.Net.Sockets.TransmitFileOptions flags, System.AsyncCallback callback, object state) { throw null; }
- public System.IAsyncResult BeginSendTo(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEP, System.AsyncCallback callback, object state) { throw null; }
+ public System.IAsyncResult BeginAccept(System.AsyncCallback? callback, object? state) { throw null; }
+ public System.IAsyncResult BeginAccept(int receiveSize, System.AsyncCallback? callback, object? state) { throw null; }
+ public System.IAsyncResult BeginAccept(System.Net.Sockets.Socket? acceptSocket, int receiveSize, System.AsyncCallback? callback, object? state) { throw null; }
+ public System.IAsyncResult BeginConnect(System.Net.EndPoint remoteEP, System.AsyncCallback? callback, object? state) { throw null; }
+ public System.IAsyncResult BeginConnect(System.Net.IPAddress address, int port, System.AsyncCallback? requestCallback, object? state) { throw null; }
+ public System.IAsyncResult BeginConnect(System.Net.IPAddress[] addresses, int port, System.AsyncCallback? requestCallback, object? state) { throw null; }
+ public System.IAsyncResult BeginConnect(string host, int port, System.AsyncCallback? requestCallback, object? state) { throw null; }
+ public System.IAsyncResult BeginDisconnect(bool reuseSocket, System.AsyncCallback? callback, object? state) { throw null; }
+ public System.IAsyncResult BeginReceive(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, System.AsyncCallback? callback, object? state) { throw null; }
+ public System.IAsyncResult? BeginReceive(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode, System.AsyncCallback? callback, object? state) { throw null; }
+ public System.IAsyncResult BeginReceive(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags, System.AsyncCallback? callback, object? state) { throw null; }
+ public System.IAsyncResult? BeginReceive(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode, System.AsyncCallback? callback, object? state) { throw null; }
+ public System.IAsyncResult BeginReceiveFrom(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, ref System.Net.EndPoint remoteEP, System.AsyncCallback? callback, object? state) { throw null; }
+ public System.IAsyncResult BeginReceiveMessageFrom(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, ref System.Net.EndPoint remoteEP, System.AsyncCallback? callback, object? state) { throw null; }
+ public System.IAsyncResult BeginSend(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, System.AsyncCallback? callback, object? state) { throw null; }
+ public System.IAsyncResult? BeginSend(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode, System.AsyncCallback? callback, object? state) { throw null; }
+ public System.IAsyncResult BeginSend(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags, System.AsyncCallback? callback, object? state) { throw null; }
+ public System.IAsyncResult? BeginSend(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode, System.AsyncCallback? callback, object? state) { throw null; }
+ public System.IAsyncResult BeginSendFile(string fileName, System.AsyncCallback? callback, object? state) { throw null; }
+ public System.IAsyncResult BeginSendFile(string? fileName, byte[]? preBuffer, byte[]? postBuffer, System.Net.Sockets.TransmitFileOptions flags, System.AsyncCallback? callback, object? state) { throw null; }
+ public System.IAsyncResult BeginSendTo(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEP, System.AsyncCallback? callback, object? state) { throw null; }
public void Bind(System.Net.EndPoint localEP) { }
public static void CancelConnectAsync(System.Net.Sockets.SocketAsyncEventArgs e) { }
public void Close() { }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public System.Net.Sockets.SocketInformation DuplicateAndClose(int targetProcessId) { throw null; }
- public System.Net.Sockets.Socket EndAccept(out byte[] buffer, System.IAsyncResult asyncResult) { throw null; }
- public System.Net.Sockets.Socket EndAccept(out byte[] buffer, out int bytesTransferred, System.IAsyncResult asyncResult) { throw null; }
+ public System.Net.Sockets.Socket EndAccept(out byte[]? buffer, System.IAsyncResult asyncResult) { throw null; }
+ public System.Net.Sockets.Socket EndAccept(out byte[]? buffer, out int bytesTransferred, System.IAsyncResult asyncResult) { throw null; }
public System.Net.Sockets.Socket EndAccept(System.IAsyncResult asyncResult) { throw null; }
public void EndConnect(System.IAsyncResult asyncResult) { }
public void EndDisconnect(System.IAsyncResult asyncResult) { }
public void EndSendFile(System.IAsyncResult asyncResult) { }
public int EndSendTo(System.IAsyncResult asyncResult) { throw null; }
~Socket() { }
- public object GetSocketOption(System.Net.Sockets.SocketOptionLevel optionLevel, System.Net.Sockets.SocketOptionName optionName) { throw null; }
+ public object? GetSocketOption(System.Net.Sockets.SocketOptionLevel optionLevel, System.Net.Sockets.SocketOptionName optionName) { throw null; }
public void GetSocketOption(System.Net.Sockets.SocketOptionLevel optionLevel, System.Net.Sockets.SocketOptionName optionName, byte[] optionValue) { }
public byte[] GetSocketOption(System.Net.Sockets.SocketOptionLevel optionLevel, System.Net.Sockets.SocketOptionName optionName, int optionLength) { throw null; }
- public int IOControl(int ioControlCode, byte[] optionInValue, byte[] optionOutValue) { throw null; }
- public int IOControl(System.Net.Sockets.IOControlCode ioControlCode, byte[] optionInValue, byte[] optionOutValue) { throw null; }
+ public int IOControl(int ioControlCode, byte[]? optionInValue, byte[]? optionOutValue) { throw null; }
+ public int IOControl(System.Net.Sockets.IOControlCode ioControlCode, byte[]? optionInValue, byte[]? optionOutValue) { throw null; }
public void Listen() { }
public void Listen(int backlog) { }
public bool Poll(int microSeconds, System.Net.Sockets.SelectMode mode) { throw null; }
public bool ReceiveFromAsync(System.Net.Sockets.SocketAsyncEventArgs e) { throw null; }
public int ReceiveMessageFrom(byte[] buffer, int offset, int size, ref System.Net.Sockets.SocketFlags socketFlags, ref System.Net.EndPoint remoteEP, out System.Net.Sockets.IPPacketInformation ipPacketInformation) { throw null; }
public bool ReceiveMessageFromAsync(System.Net.Sockets.SocketAsyncEventArgs e) { throw null; }
- public static void Select(System.Collections.IList checkRead, System.Collections.IList checkWrite, System.Collections.IList checkError, int microSeconds) { }
+ public static void Select(System.Collections.IList? checkRead, System.Collections.IList? checkWrite, System.Collections.IList? checkError, int microSeconds) { }
public int Send(byte[] buffer) { throw null; }
public int Send(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags) { throw null; }
public int Send(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode) { throw null; }
public int Send(System.ReadOnlySpan<byte> buffer, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode) { throw null; }
public bool SendAsync(System.Net.Sockets.SocketAsyncEventArgs e) { throw null; }
public void SendFile(string fileName) { }
- public void SendFile(string fileName, byte[] preBuffer, byte[] postBuffer, System.Net.Sockets.TransmitFileOptions flags) { }
+ public void SendFile(string? fileName, byte[]? preBuffer, byte[]? postBuffer, System.Net.Sockets.TransmitFileOptions flags) { }
public bool SendPacketsAsync(System.Net.Sockets.SocketAsyncEventArgs e) { throw null; }
public int SendTo(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEP) { throw null; }
public int SendTo(byte[] buffer, int size, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEP) { throw null; }
{
public SocketAsyncEventArgs() { }
public SocketAsyncEventArgs(bool unsafeSuppressExecutionContextFlow) { }
- public System.Net.Sockets.Socket AcceptSocket { get { throw null; } set { } }
- public byte[] Buffer { get { throw null; } }
- public System.Collections.Generic.IList<System.ArraySegment<byte>> BufferList { get { throw null; } set { } }
+ public System.Net.Sockets.Socket? AcceptSocket { get { throw null; } set { } }
+ public byte[]? Buffer { get { throw null; } }
+ public System.Collections.Generic.IList<System.ArraySegment<byte>>? BufferList { get { throw null; } set { } }
public int BytesTransferred { get { throw null; } }
- public System.Exception ConnectByNameError { get { throw null; } }
- public System.Net.Sockets.Socket ConnectSocket { get { throw null; } }
+ public System.Exception? ConnectByNameError { get { throw null; } }
+ public System.Net.Sockets.Socket? ConnectSocket { get { throw null; } }
public int Count { get { throw null; } }
public bool DisconnectReuseSocket { get { throw null; } set { } }
public System.Net.Sockets.SocketAsyncOperation LastOperation { get { throw null; } }
public System.Memory<byte> MemoryBuffer { get { throw null; } }
public int Offset { get { throw null; } }
public System.Net.Sockets.IPPacketInformation ReceiveMessageFromPacketInfo { get { throw null; } }
- public System.Net.EndPoint RemoteEndPoint { get { throw null; } set { } }
- public System.Net.Sockets.SendPacketsElement[] SendPacketsElements { get { throw null; } set { } }
+ public System.Net.EndPoint? RemoteEndPoint { get { throw null; } set { } }
+ public System.Net.Sockets.SendPacketsElement[]? SendPacketsElements { get { throw null; } set { } }
public System.Net.Sockets.TransmitFileOptions SendPacketsFlags { get { throw null; } set { } }
public int SendPacketsSendSize { get { throw null; } set { } }
public System.Net.Sockets.SocketError SocketError { get { throw null; } set { } }
public System.Net.Sockets.SocketFlags SocketFlags { get { throw null; } set { } }
- public object UserToken { get { throw null; } set { } }
- public event System.EventHandler<System.Net.Sockets.SocketAsyncEventArgs> Completed { add { } remove { } }
+ public object? UserToken { get { throw null; } set { } }
+ public event System.EventHandler<System.Net.Sockets.SocketAsyncEventArgs>? Completed { add { } remove { } }
public void Dispose() { }
~SocketAsyncEventArgs() { }
protected virtual void OnCompleted(System.Net.Sockets.SocketAsyncEventArgs e) { }
- public void SetBuffer(byte[] buffer, int offset, int count) { }
+ public void SetBuffer(byte[]? buffer, int offset, int count) { }
public void SetBuffer(int offset, int count) { }
public void SetBuffer(System.Memory<byte> buffer) { }
}
public static partial class SocketTaskExtensions
{
public static System.Threading.Tasks.Task<System.Net.Sockets.Socket> AcceptAsync(this System.Net.Sockets.Socket socket) { throw null; }
- public static System.Threading.Tasks.Task<System.Net.Sockets.Socket> AcceptAsync(this System.Net.Sockets.Socket socket, System.Net.Sockets.Socket acceptSocket) { throw null; }
+ public static System.Threading.Tasks.Task<System.Net.Sockets.Socket> AcceptAsync(this System.Net.Sockets.Socket socket, System.Net.Sockets.Socket? acceptSocket) { throw null; }
public static System.Threading.Tasks.Task ConnectAsync(this System.Net.Sockets.Socket socket, System.Net.EndPoint remoteEP) { throw null; }
public static System.Threading.Tasks.Task ConnectAsync(this System.Net.Sockets.Socket socket, System.Net.IPAddress address, int port) { throw null; }
public static System.Threading.Tasks.Task ConnectAsync(this System.Net.Sockets.Socket socket, System.Net.IPAddress[] addresses, int port) { throw null; }
public System.Net.Sockets.Socket Client { get { throw null; } set { } }
public bool Connected { get { throw null; } }
public bool ExclusiveAddressUse { get { throw null; } set { } }
- public System.Net.Sockets.LingerOption LingerState { get { throw null; } set { } }
+ [System.Diagnostics.CodeAnalysis.DisallowNullAttribute]
+ public System.Net.Sockets.LingerOption? LingerState { get { throw null; } set { } }
public bool NoDelay { get { throw null; } set { } }
public int ReceiveBufferSize { get { throw null; } set { } }
public int ReceiveTimeout { get { throw null; } set { } }
public int SendBufferSize { get { throw null; } set { } }
public int SendTimeout { get { throw null; } set { } }
- public System.IAsyncResult BeginConnect(System.Net.IPAddress address, int port, System.AsyncCallback requestCallback, object state) { throw null; }
- public System.IAsyncResult BeginConnect(System.Net.IPAddress[] addresses, int port, System.AsyncCallback requestCallback, object state) { throw null; }
- public System.IAsyncResult BeginConnect(string host, int port, System.AsyncCallback requestCallback, object state) { throw null; }
+ public System.IAsyncResult BeginConnect(System.Net.IPAddress address, int port, System.AsyncCallback? requestCallback, object? state) { throw null; }
+ public System.IAsyncResult BeginConnect(System.Net.IPAddress[] addresses, int port, System.AsyncCallback? requestCallback, object? state) { throw null; }
+ public System.IAsyncResult BeginConnect(string host, int port, System.AsyncCallback? requestCallback, object? state) { throw null; }
public void Close() { }
public void Connect(System.Net.IPAddress address, int port) { }
public void Connect(System.Net.IPAddress[] ipAddresses, int port) { }
public System.Net.Sockets.TcpClient AcceptTcpClient() { throw null; }
public System.Threading.Tasks.Task<System.Net.Sockets.TcpClient> AcceptTcpClientAsync() { throw null; }
public void AllowNatTraversal(bool allowed) { }
- public System.IAsyncResult BeginAcceptSocket(System.AsyncCallback callback, object state) { throw null; }
- public System.IAsyncResult BeginAcceptTcpClient(System.AsyncCallback callback, object state) { throw null; }
+ public System.IAsyncResult BeginAcceptSocket(System.AsyncCallback? callback, object? state) { throw null; }
+ public System.IAsyncResult BeginAcceptTcpClient(System.AsyncCallback? callback, object? state) { throw null; }
public static System.Net.Sockets.TcpListener Create(int port) { throw null; }
public System.Net.Sockets.Socket EndAcceptSocket(System.IAsyncResult asyncResult) { throw null; }
public System.Net.Sockets.TcpClient EndAcceptTcpClient(System.IAsyncResult asyncResult) { throw null; }
public bool MulticastLoopback { get { throw null; } set { } }
public short Ttl { get { throw null; } set { } }
public void AllowNatTraversal(bool allowed) { }
- public System.IAsyncResult BeginReceive(System.AsyncCallback requestCallback, object state) { throw null; }
- public System.IAsyncResult BeginSend(byte[] datagram, int bytes, System.AsyncCallback requestCallback, object state) { throw null; }
- public System.IAsyncResult BeginSend(byte[] datagram, int bytes, System.Net.IPEndPoint endPoint, System.AsyncCallback requestCallback, object state) { throw null; }
- public System.IAsyncResult BeginSend(byte[] datagram, int bytes, string hostname, int port, System.AsyncCallback requestCallback, object state) { throw null; }
+ public System.IAsyncResult BeginReceive(System.AsyncCallback? requestCallback, object? state) { throw null; }
+ public System.IAsyncResult BeginSend(byte[] datagram, int bytes, System.AsyncCallback? requestCallback, object? state) { throw null; }
+ public System.IAsyncResult BeginSend(byte[] datagram, int bytes, System.Net.IPEndPoint? endPoint, System.AsyncCallback? requestCallback, object? state) { throw null; }
+ public System.IAsyncResult BeginSend(byte[] datagram, int bytes, string? hostname, int port, System.AsyncCallback? requestCallback, object? state) { throw null; }
public void Close() { }
public void Connect(System.Net.IPAddress addr, int port) { }
public void Connect(System.Net.IPEndPoint endPoint) { }
public void JoinMulticastGroup(System.Net.IPAddress multicastAddr) { }
public void JoinMulticastGroup(System.Net.IPAddress multicastAddr, int timeToLive) { }
public void JoinMulticastGroup(System.Net.IPAddress multicastAddr, System.Net.IPAddress localAddress) { }
- public byte[] Receive(ref System.Net.IPEndPoint remoteEP) { throw null; }
+ public byte[] Receive([System.Diagnostics.CodeAnalysis.NotNullAttribute] ref System.Net.IPEndPoint? remoteEP) { throw null; }
public System.Threading.Tasks.Task<System.Net.Sockets.UdpReceiveResult> ReceiveAsync() { throw null; }
public int Send(byte[] dgram, int bytes) { throw null; }
- public int Send(byte[] dgram, int bytes, System.Net.IPEndPoint endPoint) { throw null; }
- public int Send(byte[] dgram, int bytes, string hostname, int port) { throw null; }
+ public int Send(byte[] dgram, int bytes, System.Net.IPEndPoint? endPoint) { throw null; }
+ public int Send(byte[] dgram, int bytes, string? hostname, int port) { throw null; }
public System.Threading.Tasks.Task<int> SendAsync(byte[] datagram, int bytes) { throw null; }
- public System.Threading.Tasks.Task<int> SendAsync(byte[] datagram, int bytes, System.Net.IPEndPoint endPoint) { throw null; }
- public System.Threading.Tasks.Task<int> SendAsync(byte[] datagram, int bytes, string hostname, int port) { throw null; }
+ public System.Threading.Tasks.Task<int> SendAsync(byte[] datagram, int bytes, System.Net.IPEndPoint? endPoint) { throw null; }
+ public System.Threading.Tasks.Task<int> SendAsync(byte[] datagram, int bytes, string? hostname, int port) { throw null; }
}
public partial struct UdpReceiveResult : System.IEquatable<System.Net.Sockets.UdpReceiveResult>
{
public byte[] Buffer { get { throw null; } }
public System.Net.IPEndPoint RemoteEndPoint { get { throw null; } }
public bool Equals(System.Net.Sockets.UdpReceiveResult other) { throw null; }
- public override bool Equals(object obj) { throw null; }
+ public override bool Equals(object? obj) { throw null; }
public override int GetHashCode() { throw null; }
public static bool operator ==(System.Net.Sockets.UdpReceiveResult left, System.Net.Sockets.UdpReceiveResult right) { throw null; }
public static bool operator !=(System.Net.Sockets.UdpReceiveResult left, System.Net.Sockets.UdpReceiveResult right) { throw null; }
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>$(NetCoreAppCurrent)</TargetFrameworks>
+ <Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<Compile Include="System.Net.Sockets.cs" />
<AssemblyName>System.Net.Sockets</AssemblyName>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<TargetFrameworks>$(NetCoreAppCurrent)-Windows_NT;$(NetCoreAppCurrent)-Unix</TargetFrameworks>
+ <Nullable>enable</Nullable>
</PropertyGroup>
<PropertyGroup>
<!-- SYSTEM_NET_SOCKETS_DLL is required to allow source-level code sharing for types defined within the
<Reference Include="System.Threading.Overlapped" />
<Reference Include="System.Threading.ThreadPool" />
</ItemGroup>
- <ItemGroup Condition="'$(TargetsUnix)' == 'true'">
- <Reference Include="System.Threading.ThreadPool" />
- </ItemGroup>
</Project>
\ No newline at end of file
// AcceptOverlappedAsyncResult - used to take care of storage for async Socket BeginAccept call.
internal sealed partial class AcceptOverlappedAsyncResult : BaseOverlappedAsyncResult
{
- private Socket _acceptedSocket;
+ private Socket? _acceptedSocket;
- internal Socket AcceptSocket
+ internal Socket? AcceptSocket
{
set
{
if (errorCode == SocketError.Success)
{
+ Debug.Assert(_listenSocket._rightEndPoint != null);
+
Internals.SocketAddress remoteSocketAddress = IPEndPointExtensions.Serialize(_listenSocket._rightEndPoint);
System.Buffer.BlockCopy(socketAddress, 0, remoteSocketAddress.Buffer, 0, socketAddressLen);
base.CompletionCallback(0, errorCode);
}
- internal override object PostCompletion(int numBytes)
+ internal override object? PostCompletion(int numBytes)
{
_numBytes = numBytes;
return (SocketError)ErrorCode == SocketError.Success ? _acceptedSocket : null;
// AcceptOverlappedAsyncResult - used to take care of storage for async Socket BeginAccept call.
internal sealed partial class AcceptOverlappedAsyncResult : BaseOverlappedAsyncResult
{
- private Socket _acceptSocket;
+ private Socket? _acceptSocket;
private int _addressBufferLength;
// This method will be called by us when the IO completes synchronously and
// by the ThreadPool when the IO completes asynchronously. (only called on WinNT)
- internal override object PostCompletion(int numBytes)
+ internal override object? PostCompletion(int numBytes)
{
SocketError errorCode = (SocketError)ErrorCode;
- Internals.SocketAddress remoteSocketAddress = null;
+ Internals.SocketAddress? remoteSocketAddress = null;
if (errorCode == SocketError.Success)
{
_numBytes = numBytes;
if (NetEventSource.IsEnabled) LogBuffer(numBytes);
// get the endpoint
- remoteSocketAddress = IPEndPointExtensions.Serialize(_listenSocket._rightEndPoint);
+ remoteSocketAddress = IPEndPointExtensions.Serialize(_listenSocket._rightEndPoint!);
IntPtr localAddr;
int localAddrLength;
safeHandle.DangerousAddRef(ref refAdded);
IntPtr handle = safeHandle.DangerousGetHandle();
+ Debug.Assert(_buffer != null);
_listenSocket.GetAcceptExSockaddrs(
Marshal.UnsafeAddrOfPinnedArrayElement(_buffer, 0),
_buffer.Length - (_addressBufferLength * 2),
Marshal.Copy(remoteAddr, remoteSocketAddress.Buffer, 0, remoteSocketAddress.Size);
errorCode = Interop.Winsock.setsockopt(
- _acceptSocket.SafeHandle,
+ _acceptSocket!.SafeHandle,
SocketOptionLevel.Socket,
SocketOptionName.UpdateAcceptContext,
ref handle,
return null;
}
- return _listenSocket.UpdateAcceptSocket(_acceptSocket, _listenSocket._rightEndPoint.Create(remoteSocketAddress));
+ return _listenSocket.UpdateAcceptSocket(_acceptSocket!, _listenSocket._rightEndPoint!.Create(remoteSocketAddress!));
}
// SetUnmanagedStructures
// condition where tracing is disabled between a calling check and here, in which case the assert
// may fire erroneously.
Debug.Assert(NetEventSource.IsEnabled);
+ Debug.Assert(_buffer != null);
if (size > -1)
{
internal sealed partial class AcceptOverlappedAsyncResult : BaseOverlappedAsyncResult
{
private readonly Socket _listenSocket;
- private byte[] _buffer;
+ private byte[]? _buffer;
- internal AcceptOverlappedAsyncResult(Socket listenSocket, object asyncState, AsyncCallback asyncCallback) :
+ internal AcceptOverlappedAsyncResult(Socket listenSocket, object? asyncState, AsyncCallback? asyncCallback) :
base(listenSocket, asyncState, asyncCallback)
{
_listenSocket = listenSocket;
}
- internal byte[] Buffer
+ internal byte[]? Buffer
{
get
{
// BeginReceive, BeginReceiveFrom, BeginSendFile, and BeginAccept calls.
internal partial class BaseOverlappedAsyncResult : ContextAwareResult
{
- public BaseOverlappedAsyncResult(Socket socket, object asyncState, AsyncCallback asyncCallback)
+ public BaseOverlappedAsyncResult(Socket socket, object? asyncState, AsyncCallback? asyncCallback)
: base(socket, asyncState, asyncCallback)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, socket);
internal partial class BaseOverlappedAsyncResult : ContextAwareResult
{
private int _cleanupCount;
- private SafeNativeOverlapped _nativeOverlapped;
+ private SafeNativeOverlapped? _nativeOverlapped;
// The WinNT Completion Port callback.
private static readonly unsafe IOCompletionCallback s_ioCallback = new IOCompletionCallback(CompletionPortCallback);
- internal BaseOverlappedAsyncResult(Socket socket, object asyncState, AsyncCallback asyncCallback)
+ internal BaseOverlappedAsyncResult(Socket socket, object? asyncState, AsyncCallback? asyncCallback)
: base(socket, asyncState, asyncCallback)
{
_cleanupCount = 1;
// These calls are outside the runtime and are unmanaged code, so we need
// to prepare specific structures and ints that lie in unmanaged memory
// since the overlapped calls may complete asynchronously.
- internal void SetUnmanagedStructures(object objectsToPin)
+ internal void SetUnmanagedStructures(object? objectsToPin)
{
Socket s = (Socket)AsyncObject;
using (DebugThreadTracking.SetThreadKind(ThreadKinds.System))
{
#endif
- BaseOverlappedAsyncResult asyncResult = (BaseOverlappedAsyncResult)ThreadPoolBoundHandle.GetNativeOverlappedState(nativeOverlapped);
+ BaseOverlappedAsyncResult asyncResult = (BaseOverlappedAsyncResult)ThreadPoolBoundHandle.GetNativeOverlappedState(nativeOverlapped)!;
if (asyncResult.InternalPeekCompleted)
{
// or receiving data after shutdown (SD_RECV)). With Winsock/TCP stack rewrite in longhorn, there may
// be other differences as well."
- Socket socket = asyncResult.AsyncObject as Socket;
+ Socket? socket = asyncResult.AsyncObject as Socket;
if (socket == null)
{
socketError = SocketError.NotSocket;
private void CompletionCallback(int numBytes, SocketError socketError)
{
ErrorCode = (int)socketError;
- object result = PostCompletion(numBytes);
+ object? result = PostCompletion(numBytes);
ReleaseUnmanagedStructures(); // must come after PostCompletion, as overrides may use these resources
InvokeCallback(result);
}
- internal unsafe NativeOverlapped* DangerousOverlappedPointer => (NativeOverlapped*)_nativeOverlapped.DangerousGetHandle();
+ internal unsafe NativeOverlapped* DangerousOverlappedPointer => (NativeOverlapped*)_nativeOverlapped!.DangerousGetHandle();
// Check the result of the overlapped operation.
// Handle synchronous success by completing the asyncResult here.
{
// Free the unmanaged memory if allocated.
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
- _nativeOverlapped.Dispose();
+ _nativeOverlapped!.Dispose();
_nativeOverlapped = null;
GC.SuppressFinalize(this);
}
internal int _numBytes;
// PostCompletion returns the result object to be set before the user's callback is invoked.
- internal virtual object PostCompletion(int numBytes)
+ internal virtual object? PostCompletion(int numBytes)
{
_numBytes = numBytes;
return s_resultObjectSentinel; // return sentinel rather than boxing numBytes
}
// This method is called by base.CompletionPortCallback base.OverlappedCallback as part of IO completion
- internal override object PostCompletion(int numBytes)
+ internal override object? PostCompletion(int numBytes)
{
var errorCode = (SocketError)ErrorCode;
if (errorCode == SocketError.Success)
internal sealed partial class ConnectOverlappedAsyncResult : BaseOverlappedAsyncResult
{
// This method is called by base.CompletionPortCallback base.OverlappedCallback as part of IO completion
- internal override object PostCompletion(int numBytes)
+ internal override object? PostCompletion(int numBytes)
{
SocketError errorCode = (SocketError)ErrorCode;
Socket socket = (Socket)AsyncObject;
{
private readonly EndPoint _endPoint;
- internal ConnectOverlappedAsyncResult(Socket socket, EndPoint endPoint, object asyncState, AsyncCallback asyncCallback) :
+ internal ConnectOverlappedAsyncResult(Socket socket, EndPoint endPoint, object? asyncState, AsyncCallback? asyncCallback) :
base(socket, asyncState, asyncCallback)
{
_endPoint = endPoint;
// DisconnectOverlappedAsyncResult - used to take care of storage for async Socket BeginDisconnect call.
internal sealed partial class DisconnectOverlappedAsyncResult : BaseOverlappedAsyncResult
{
- internal DisconnectOverlappedAsyncResult(Socket socket, object asyncState, AsyncCallback asyncCallback) :
+ internal DisconnectOverlappedAsyncResult(Socket socket, object? asyncState, AsyncCallback? asyncCallback) :
base(socket, asyncState, asyncCallback)
{
}
// This method will be called by us when the IO completes synchronously and
// by the ThreadPool when the IO completes asynchronously.
- internal override object PostCompletion(int numBytes)
+ internal override object? PostCompletion(int numBytes)
{
if (ErrorCode == (int)SocketError.Success)
{
private readonly ProtocolType _protocolType;
private readonly object _lockObject;
- private AcceptExDelegate _acceptEx;
- private GetAcceptExSockaddrsDelegate _getAcceptExSockaddrs;
- private ConnectExDelegate _connectEx;
- private TransmitPacketsDelegate _transmitPackets;
+ private AcceptExDelegate? _acceptEx;
+ private GetAcceptExSockaddrsDelegate? _getAcceptExSockaddrs;
+ private ConnectExDelegate? _connectEx;
+ private TransmitPacketsDelegate? _transmitPackets;
- private DisconnectExDelegate _disconnectEx;
- private DisconnectExDelegateBlocking _disconnectExBlocking;
+ private DisconnectExDelegate? _disconnectEx;
+ private DisconnectExDelegateBlocking? _disconnectExBlocking;
- private WSARecvMsgDelegate _recvMsg;
- private WSARecvMsgDelegateBlocking _recvMsgBlocking;
+ private WSARecvMsgDelegate? _recvMsg;
+ private WSARecvMsgDelegateBlocking? _recvMsgBlocking;
private DynamicWinsockMethods(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
{
else if (typeof(T) == typeof(DisconnectExDelegate))
{
EnsureDisconnectEx(socketHandle);
+ Debug.Assert(_disconnectEx != null);
return (T)(object)_disconnectEx;
}
else if (typeof(T) == typeof(DisconnectExDelegateBlocking))
{
EnsureDisconnectEx(socketHandle);
+ Debug.Assert(_disconnectExBlocking != null);
return (T)(object)_disconnectExBlocking;
}
else if (typeof(T) == typeof(WSARecvMsgDelegate))
private static readonly bool s_supportsKeepAliveViaSocketOption = SupportsKeepAliveViaSocketOption();
private static readonly ConditionalWeakTable<SafeSocketHandle, IOControlKeepAlive> s_socketKeepAliveTable = new ConditionalWeakTable<SafeSocketHandle, IOControlKeepAlive>();
[ThreadStatic]
- private static byte[] s_keepAliveValuesBuffer;
+ private static byte[]? s_keepAliveValuesBuffer;
private uint _timeMs = WindowsDefaultTimeMs;
private uint _intervalMs = WindowsDefaultIntervalMs;
public static int Get(SafeSocketHandle handle, SocketOptionName optionName)
{
- if (s_socketKeepAliveTable.TryGetValue(handle, out IOControlKeepAlive ioControlKeepAlive))
+ if (s_socketKeepAliveTable.TryGetValue(handle, out IOControlKeepAlive? ioControlKeepAlive))
{
return optionName == SocketOptionName.TcpKeepAliveTime ?
MillisecondsToSeconds(ioControlKeepAlive._timeMs) :
public static bool operator ==(IPPacketInformation packetInformation1, IPPacketInformation packetInformation2)
{
return packetInformation1._networkInterface == packetInformation2._networkInterface &&
- (packetInformation1._address == null && packetInformation2._address == null || packetInformation1._address.Equals(packetInformation2._address));
+ ((packetInformation1._address == null && packetInformation2._address == null) ||
+ (packetInformation1._address != null && packetInformation1._address.Equals(packetInformation2._address)));
}
public static bool operator !=(IPPacketInformation packetInformation1, IPPacketInformation packetInformation2)
return !(packetInformation1 == packetInformation2);
}
- public override bool Equals(object comparand) =>
+ public override bool Equals(object? comparand) =>
comparand is IPPacketInformation other && this == other;
public override int GetHashCode()
public class MulticastOption
{
private IPAddress _group;
- private IPAddress _localAddress;
+ private IPAddress? _localAddress;
private int _ifIndex;
// Creates a new instance of the MulticastOption class with the specified IP address
throw new ArgumentNullException(nameof(mcint));
}
- Group = group;
+ _group = group;
LocalAddress = mcint;
}
throw new ArgumentOutOfRangeException(nameof(interfaceIndex));
}
- Group = group;
+ _group = group;
_ifIndex = interfaceIndex;
}
throw new ArgumentNullException(nameof(group));
}
- Group = group;
+ _group = group;
LocalAddress = IPAddress.Any;
}
}
// Sets the local address of a multicast group.
- public IPAddress LocalAddress
+ public IPAddress? LocalAddress
{
get
{
throw new ArgumentOutOfRangeException(nameof(ifindex));
}
- Group = group;
+ _group = group;
InterfaceIndex = ifindex;
}
throw new ArgumentNullException(nameof(group));
}
- Group = group;
+ _group = group;
InterfaceIndex = 0;
}
// on behalf of a single user call to ConnectAsync with a DnsEndPoint
internal abstract class MultipleConnectAsync
{
- protected SocketAsyncEventArgs _userArgs;
- protected SocketAsyncEventArgs _internalArgs;
+ protected SocketAsyncEventArgs? _userArgs;
+ protected SocketAsyncEventArgs? _internalArgs;
- protected DnsEndPoint _endPoint;
- protected IPAddress[] _addressList;
+ protected DnsEndPoint? _endPoint;
+ protected IPAddress[]? _addressList;
protected int _nextAddress;
private enum State
// false if it has failed synchronously.
private bool DoDnsCallback(IAsyncResult result, bool sync)
{
- Exception exception = null;
+ Exception? exception = null;
lock (_lockObject)
{
_internalArgs = new SocketAsyncEventArgs();
_internalArgs.Completed += InternalConnectCallback;
- _internalArgs.CopyBufferFrom(_userArgs);
+ _internalArgs.CopyBufferFrom(_userArgs!);
exception = AttemptConnection();
// Callback which fires when an internal connection attempt completes.
// If it failed and there are more addresses to try, do it.
- private void InternalConnectCallback(object sender, SocketAsyncEventArgs args)
+ private void InternalConnectCallback(object? sender, SocketAsyncEventArgs args)
{
- Exception exception = null;
+ Exception? exception = null;
lock (_lockObject)
{
// Keep track of this because it will be overwritten by AttemptConnection
SocketError currentFailure = args.SocketError;
- Exception connectException = AttemptConnection();
+ Exception? connectException = AttemptConnection();
if (connectException == null)
{
}
else
{
- SocketException socketException = connectException as SocketException;
+ SocketException? socketException = connectException as SocketException;
if (socketException != null && socketException.SocketErrorCode == SocketError.NoData)
{
// If the error is NoData, that means there are no more IPAddresses to attempt
// Called to initiate a connection attempt to the next address in the list. Returns an exception
// if the attempt failed synchronously, or null if it was successfully initiated.
- private Exception AttemptConnection()
+ private Exception? AttemptConnection()
{
try
{
- Socket attemptSocket;
- IPAddress attemptAddress = GetNextAddress(out attemptSocket);
+ Socket? attemptSocket;
+ IPAddress? attemptAddress = GetNextAddress(out attemptSocket);
if (attemptAddress == null)
{
return new SocketException((int)SocketError.NoData);
}
- _internalArgs.RemoteEndPoint = new IPEndPoint(attemptAddress, _endPoint.Port);
+ _internalArgs!.RemoteEndPoint = new IPEndPoint(attemptAddress, _endPoint!.Port);
- return AttemptConnection(attemptSocket, _internalArgs);
+ return AttemptConnection(attemptSocket!, _internalArgs);
}
catch (Exception e)
{
}
}
- private Exception AttemptConnection(Socket attemptSocket, SocketAsyncEventArgs args)
+ private Exception? AttemptConnection(Socket attemptSocket, SocketAsyncEventArgs args)
{
try
{
private void Succeed()
{
OnSucceed();
- _userArgs.FinishWrapperConnectSuccess(_internalArgs.ConnectSocket, _internalArgs.BytesTransferred, _internalArgs.SocketFlags);
+ _userArgs!.FinishWrapperConnectSuccess(_internalArgs!.ConnectSocket, _internalArgs.BytesTransferred, _internalArgs.SocketFlags);
_internalArgs.Dispose();
}
_internalArgs.Dispose();
}
- SocketException socketException = e as SocketException;
+ SocketException? socketException = e as SocketException;
if (socketException != null)
{
- _userArgs.FinishConnectByNameSyncFailure(socketException, 0, SocketFlags.None);
+ _userArgs!.FinishConnectByNameSyncFailure(socketException, 0, SocketFlags.None);
}
else
{
_internalArgs.Dispose();
}
- _userArgs.FinishConnectByNameAsyncFailure(e, 0, SocketFlags.None);
+ _userArgs!.FinishConnectByNameAsyncFailure(e, 0, SocketFlags.None);
}
public void Cancel()
}
// Call AsyncFail on a threadpool thread so it's asynchronous with respect to Cancel().
- private void CallAsyncFail(object ignored)
+ private void CallAsyncFail(object? ignored)
{
AsyncFail(new SocketException((int)SocketError.OperationAborted));
}
- protected abstract IPAddress GetNextAddress(out Socket attemptSocket);
+ protected abstract IPAddress? GetNextAddress(out Socket? attemptSocket);
}
// Used when the instance ConnectAsync method is called, or when the DnsEndPoint specified
_userSocket = userSocket;
}
- protected override IPAddress GetNextAddress(out Socket attemptSocket)
+ protected override IPAddress? GetNextAddress(out Socket? attemptSocket)
{
_socket.ReplaceHandleIfNecessaryAfterFailedConnect();
- IPAddress rval = null;
+ IPAddress? rval = null;
do
{
- if (_nextAddress >= _addressList.Length)
+ if (_nextAddress >= _addressList!.Length)
{
attemptSocket = null;
return null;
// ahead of time, so we create both IPv4 and IPv6 sockets.
internal sealed class DualSocketMultipleConnectAsync : MultipleConnectAsync
{
- private readonly Socket _socket4;
- private readonly Socket _socket6;
+ private readonly Socket? _socket4;
+ private readonly Socket? _socket6;
public DualSocketMultipleConnectAsync(SocketType socketType, ProtocolType protocolType)
{
}
}
- protected override IPAddress GetNextAddress(out Socket attemptSocket)
+ protected override IPAddress? GetNextAddress(out Socket? attemptSocket)
{
- IPAddress rval = null;
+ IPAddress? rval = null;
attemptSocket = null;
while (attemptSocket == null)
{
- if (_nextAddress >= _addressList.Length)
+ if (_nextAddress >= _addressList!.Length)
{
return null;
}
private const int NotLoggedFileId = ConnectedAsyncDnsId + 1;
[NonEvent]
- public static void Accepted(Socket socket, object remoteEp, object localEp)
+ public static void Accepted(Socket socket, object? remoteEp, object? localEp)
{
if (IsEnabled)
{
}
[NonEvent]
- public static void Connected(Socket socket, object localEp, object remoteEp)
+ public static void Connected(Socket socket, object? localEp, object? remoteEp)
{
if (IsEnabled)
{
/// <param name="buffer">The buffer to be logged.</param>
/// <param name="memberName">The calling member.</param>
[NonEvent]
- public static void DumpBuffer(object thisOrContextObject, Memory<byte> buffer, [CallerMemberName] string memberName = null)
+ public static void DumpBuffer(object thisOrContextObject, Memory<byte> buffer, [CallerMemberName] string? memberName = null)
{
DumpBuffer(thisOrContextObject, buffer, 0, buffer.Length, memberName);
}
/// <param name="count">The number of bytes to log.</param>
/// <param name="memberName">The calling member.</param>
[NonEvent]
- public static void DumpBuffer(object thisOrContextObject, Memory<byte> buffer, int offset, int count, [CallerMemberName] string memberName = null)
+ public static void DumpBuffer(object thisOrContextObject, Memory<byte> buffer, int offset, int count, [CallerMemberName] string? memberName = null)
{
if (IsEnabled)
{
buffer = buffer.Slice(offset, Math.Min(count, MaxDumpSize));
byte[] slice = MemoryMarshal.TryGetArray(buffer, out ArraySegment<byte> arraySegment) && arraySegment.Offset == 0 && arraySegment.Count == buffer.Length ?
- arraySegment.Array :
+ arraySegment.Array! :
buffer.ToArray();
Log.DumpBuffer(IdOf(thisOrContextObject), memberName, slice);
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
- int timeout = (int)_streamSocket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout);
+ int timeout = (int)_streamSocket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout)!;
if (timeout == 0)
{
return -1;
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
{
#endif
- int timeout = (int)_streamSocket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout);
+ int timeout = (int)_streamSocket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout)!;
if (timeout == 0)
{
return -1;
// Returns:
//
// An IASyncResult, representing the read.
- public override IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback callback, object state)
+ public override IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback? callback, object? state)
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
// Returns:
//
// An IASyncResult, representing the write.
- public override IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback callback, object state)
+ public override IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback? callback, object? state)
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
return _socketAddressSize;
}
- public void CompletionCallback(int numBytes, byte[] socketAddress, int socketAddressSize, SocketFlags receivedFlags, SocketError errorCode)
+ public void CompletionCallback(int numBytes, byte[]? socketAddress, int socketAddressSize, SocketFlags receivedFlags, SocketError errorCode)
{
if (_socketAddress != null)
{
internal partial class OverlappedAsyncResult : BaseOverlappedAsyncResult
{
internal WSABuffer _singleBuffer;
- internal WSABuffer[] _wsaBuffers;
+ internal WSABuffer[]? _wsaBuffers;
internal IntPtr GetSocketAddressPtr()
{
- return Marshal.UnsafeAddrOfPinnedArrayElement(_socketAddress.Buffer, 0);
+ return Marshal.UnsafeAddrOfPinnedArrayElement(_socketAddress!.Buffer, 0);
}
internal IntPtr GetSocketAddressSizePtr()
{
- return Marshal.UnsafeAddrOfPinnedArrayElement(_socketAddress.Buffer, _socketAddress.GetAddressSizeOffset());
+ return Marshal.UnsafeAddrOfPinnedArrayElement(_socketAddress!.Buffer, _socketAddress.GetAddressSizeOffset());
}
internal unsafe int GetSocketAddressSize()
// These calls are outside the runtime and are unmanaged code, so we need
// to prepare specific structures and ints that lie in unmanaged memory
// since the overlapped calls may complete asynchronously.
- internal void SetUnmanagedStructures(byte[] buffer, int offset, int size, Internals.SocketAddress socketAddress)
+ internal void SetUnmanagedStructures(byte[] buffer, int offset, int size, Internals.SocketAddress? socketAddress)
{
// Fill in Buffer Array structure that will be used for our send/recv Buffer
_socketAddress = socketAddress;
if (_socketAddress != null)
{
- object[] objectsToPin = null;
- objectsToPin = new object[2];
+ object[] objectsToPin = new object[2];
objectsToPin[0] = buffer;
_socketAddress.CopyAddressSizeIntoBuffer();
object[] objectsToPin = new object[count];
for (int i = 0; i < count; i++)
{
- objectsToPin[i] = buffersCopy[i].Array;
+ objectsToPin[i] = buffersCopy[i].Array!;
}
base.SetUnmanagedStructures(objectsToPin);
for (int i = 0; i < count; i++)
{
_wsaBuffers[i].Length = buffersCopy[i].Count;
- _wsaBuffers[i].Pointer = Marshal.UnsafeAddrOfPinnedArrayElement(buffersCopy[i].Array, buffersCopy[i].Offset);
+ _wsaBuffers[i].Pointer = Marshal.UnsafeAddrOfPinnedArrayElement(buffersCopy[i].Array!, buffersCopy[i].Offset);
}
}
// 1) completed synchronously.
// 2) was pended.
// 3) failed.
- internal override object PostCompletion(int numBytes)
+ internal override object? PostCompletion(int numBytes)
{
if (ErrorCode == 0 && NetEventSource.IsEnabled)
{
// from the BeginSend, BeginSendTo, BeginReceive, BeginReceiveFrom calls.
internal partial class OverlappedAsyncResult : BaseOverlappedAsyncResult
{
- private Internals.SocketAddress _socketAddress;
+ private Internals.SocketAddress? _socketAddress;
- internal OverlappedAsyncResult(Socket socket, object asyncState, AsyncCallback asyncCallback) :
+ internal OverlappedAsyncResult(Socket socket, object? asyncState, AsyncCallback? asyncCallback) :
base(socket, asyncState, asyncCallback)
{
}
- internal Internals.SocketAddress SocketAddress
+ internal Internals.SocketAddress? SocketAddress
{
get { return _socketAddress; }
set { _socketAddress = value; }
internal sealed class OriginalAddressOverlappedAsyncResult : OverlappedAsyncResult
{
- internal OriginalAddressOverlappedAsyncResult(Socket socket, object asyncState, AsyncCallback asyncCallback) :
+ internal OriginalAddressOverlappedAsyncResult(Socket socket, object? asyncState, AsyncCallback? asyncCallback) :
base(socket, asyncState, asyncCallback)
{
}
- internal Internals.SocketAddress SocketAddressOriginal { get; set; }
+ internal Internals.SocketAddress? SocketAddressOriginal { get; set; }
}
}
{
private Interop.Winsock.WSAMsg* _message;
private WSABuffer* _wsaBuffer;
- private byte[] _wsaBufferArray;
- private byte[] _controlBuffer;
- internal byte[] _messageBuffer;
+ private byte[]? _wsaBufferArray;
+ private byte[]? _controlBuffer;
+ internal byte[]? _messageBuffer;
private IntPtr GetSocketAddressSizePtr()
{
- return Marshal.UnsafeAddrOfPinnedArrayElement(_socketAddress.Buffer, _socketAddress.GetAddressSizeOffset());
+ return Marshal.UnsafeAddrOfPinnedArrayElement(_socketAddress!.Buffer, _socketAddress.GetAddressSizeOffset());
}
internal unsafe int GetSocketAddressSize()
private unsafe void InitIPPacketInformation()
{
- if (_controlBuffer.Length == sizeof(Interop.Winsock.ControlData))
+ int? controlBufferLength = _controlBuffer?.Length;
+ if (controlBufferLength == sizeof(Interop.Winsock.ControlData))
{
// IPv4
_ipPacketInformation = SocketPal.GetIPPacketInformation((Interop.Winsock.ControlData*)_message->controlBuffer.Pointer);
}
- else if (_controlBuffer.Length == sizeof(Interop.Winsock.ControlDataIPv6))
+ else if (controlBufferLength == sizeof(Interop.Winsock.ControlDataIPv6))
{
// IPv6
_ipPacketInformation = SocketPal.GetIPPacketInformation((Interop.Winsock.ControlDataIPv6*)_message->controlBuffer.Pointer);
base.ForceReleaseUnmanagedStructures();
}
- internal override object PostCompletion(int numBytes)
+ internal override object? PostCompletion(int numBytes)
{
InitIPPacketInformation();
if (ErrorCode == 0 && NetEventSource.IsEnabled)
{
internal unsafe sealed partial class ReceiveMessageOverlappedAsyncResult : BaseOverlappedAsyncResult
{
- private Internals.SocketAddress _socketAddressOriginal;
- private Internals.SocketAddress _socketAddress;
+ private Internals.SocketAddress? _socketAddressOriginal;
+ private Internals.SocketAddress? _socketAddress;
private SocketFlags _socketFlags;
private IPPacketInformation _ipPacketInformation;
- internal ReceiveMessageOverlappedAsyncResult(Socket socket, object asyncState, AsyncCallback asyncCallback) :
+ internal ReceiveMessageOverlappedAsyncResult(Socket socket, object? asyncState, AsyncCallback? asyncCallback) :
base(socket, asyncState, asyncCallback)
{ }
- internal Internals.SocketAddress SocketAddress
+ internal Internals.SocketAddress? SocketAddress
{
get
{
}
}
- internal Internals.SocketAddress SocketAddressOriginal
+ internal Internals.SocketAddress? SocketAddressOriginal
{
get
{
private int _sendTimeout = -1;
private bool _nonBlocking;
private bool _underlyingHandleNonBlocking;
- private SocketAsyncContext _asyncContext;
+ private SocketAsyncContext? _asyncContext;
private TrackedSocketOptions _trackedOptions;
internal bool LastConnectFailed { get; set; }
Interlocked.CompareExchange(ref _asyncContext, new SocketAsyncContext(this), null);
}
- return _asyncContext;
+ return _asyncContext!;
}
}
{
public partial class SafeSocketHandle
{
- private ThreadPoolBoundHandle _iocpBoundHandle;
+ private ThreadPoolBoundHandle? _iocpBoundHandle;
private bool _skipCompletionPortOnSuccess;
internal void SetExposed() { /* nop */ }
- internal ThreadPoolBoundHandle IOCPBoundHandle
+ internal ThreadPoolBoundHandle? IOCPBoundHandle
{
get
{
}
}
- internal ThreadPoolBoundHandle GetThreadPoolBoundHandle() => !_released ? _iocpBoundHandle : null;
+ internal ThreadPoolBoundHandle? GetThreadPoolBoundHandle() => !_released ? _iocpBoundHandle : null;
// Binds the Socket Win32 Handle to the ThreadPool's CompletionPort.
internal ThreadPoolBoundHandle GetOrAllocateThreadPoolBoundHandle(bool trySkipCompletionPortOnSuccess)
lock (this)
{
- ThreadPoolBoundHandle boundHandle = _iocpBoundHandle;
+ ThreadPoolBoundHandle? boundHandle = _iocpBoundHandle;
if (boundHandle == null)
{
return errorCode;
}
- private static void ThrowSocketDisposedException(Exception innerException = null) =>
+ private static void ThrowSocketDisposedException(Exception? innerException = null) =>
throw new ObjectDisposedException(typeof(Socket).FullName, innerException);
}
}
Initialize(null, null, buffer, offset, count, endOfPacket);
}
- private void Initialize(string filePath, FileStream fileStream, byte[] buffer, long offset, int count, bool endOfPacket)
+ private void Initialize(string? filePath, FileStream? fileStream, byte[]? buffer, long offset, int count, bool endOfPacket)
{
FilePath = filePath;
FileStream = fileStream;
EndOfPacket = endOfPacket;
}
- public string FilePath { get; private set; }
+ public string? FilePath { get; private set; }
- public FileStream FileStream { get; private set; }
+ public FileStream? FileStream { get; private set; }
- public byte[] Buffer { get; private set; }
+ public byte[]? Buffer { get; private set; }
public int Count { get; private set; }
public partial class Socket
{
/// <summary>Handler for completed AcceptAsync operations.</summary>
- private static readonly EventHandler<SocketAsyncEventArgs> AcceptCompletedHandler = (s, e) => CompleteAccept((Socket)s, (TaskSocketAsyncEventArgs<Socket>)e);
+ private static readonly EventHandler<SocketAsyncEventArgs> AcceptCompletedHandler = (s, e) => CompleteAccept((Socket)s!, (TaskSocketAsyncEventArgs<Socket>)e);
/// <summary>Handler for completed ReceiveAsync operations.</summary>
- private static readonly EventHandler<SocketAsyncEventArgs> ReceiveCompletedHandler = (s, e) => CompleteSendReceive((Socket)s, (Int32TaskSocketAsyncEventArgs)e, isReceive: true);
+ private static readonly EventHandler<SocketAsyncEventArgs> ReceiveCompletedHandler = (s, e) => CompleteSendReceive((Socket)s!, (Int32TaskSocketAsyncEventArgs)e, isReceive: true);
/// <summary>Handler for completed SendAsync operations.</summary>
- private static readonly EventHandler<SocketAsyncEventArgs> SendCompletedHandler = (s, e) => CompleteSendReceive((Socket)s, (Int32TaskSocketAsyncEventArgs)e, isReceive: false);
+ private static readonly EventHandler<SocketAsyncEventArgs> SendCompletedHandler = (s, e) => CompleteSendReceive((Socket)s!, (Int32TaskSocketAsyncEventArgs)e, isReceive: false);
/// <summary>
/// Sentinel that can be stored into one of the Socket cached fields to indicate that an instance
/// was previously created but is currently being used by another concurrent operation.
private static readonly Task<int> s_zeroTask = Task.FromResult(0);
/// <summary>Cached event args used with Task-based async operations.</summary>
- private CachedEventArgs _cachedTaskEventArgs;
+ private CachedEventArgs? _cachedTaskEventArgs;
private CachedEventArgs EventArgs => LazyInitializer.EnsureInitialized(ref _cachedTaskEventArgs, () => new CachedEventArgs());
- internal Task<Socket> AcceptAsync(Socket acceptSocket)
+ internal Task<Socket> AcceptAsync(Socket? acceptSocket)
{
// Get any cached SocketAsyncEventArg we may have.
- TaskSocketAsyncEventArgs<Socket> saea = Interlocked.Exchange(ref EventArgs.TaskAccept, s_rentedSocketSentinel);
+ TaskSocketAsyncEventArgs<Socket>? saea = Interlocked.Exchange(ref EventArgs.TaskAccept, s_rentedSocketSentinel);
if (saea == s_rentedSocketSentinel)
{
// An instance was once created (or is currently being created elsewhere), but some other
{
// The operation completed synchronously. Get a task for it.
t = saea.SocketError == SocketError.Success ?
- Task.FromResult(saea.AcceptSocket) :
+ Task.FromResult(saea.AcceptSocket!) :
Task.FromException<Socket>(GetException(saea.SocketError));
// There won't be a callback, and we're done with the SAEA, so return it to the pool.
}
/// <summary>Implements Task-returning AcceptAsync on top of Begin/EndAsync.</summary>
- private Task<Socket> AcceptAsyncApm(Socket acceptSocket)
+ private Task<Socket> AcceptAsyncApm(Socket? acceptSocket)
{
var tcs = new TaskCompletionSource<Socket>(this);
BeginAccept(acceptSocket, 0, iar =>
{
- var innerTcs = (TaskCompletionSource<Socket>)iar.AsyncState;
- try { innerTcs.TrySetResult(((Socket)innerTcs.Task.AsyncState).EndAccept(iar)); }
+ var innerTcs = (TaskCompletionSource<Socket>)iar.AsyncState!;
+ try { innerTcs.TrySetResult(((Socket)innerTcs.Task.AsyncState!).EndAccept(iar)); }
catch (Exception e) { innerTcs.TrySetException(e); }
}, tcs);
return tcs.Task;
var tcs = new TaskCompletionSource<bool>(this);
BeginConnect(remoteEP, iar =>
{
- var innerTcs = (TaskCompletionSource<bool>)iar.AsyncState;
+ var innerTcs = (TaskCompletionSource<bool>)iar.AsyncState!;
try
{
- ((Socket)innerTcs.Task.AsyncState).EndConnect(iar);
+ ((Socket)innerTcs.Task.AsyncState!).EndConnect(iar);
innerTcs.TrySetResult(true);
}
catch (Exception e) { innerTcs.TrySetException(e); }
var tcs = new TaskCompletionSource<bool>(this);
BeginConnect(address, port, iar =>
{
- var innerTcs = (TaskCompletionSource<bool>)iar.AsyncState;
+ var innerTcs = (TaskCompletionSource<bool>)iar.AsyncState!;
try
{
- ((Socket)innerTcs.Task.AsyncState).EndConnect(iar);
+ ((Socket)innerTcs.Task.AsyncState!).EndConnect(iar);
innerTcs.TrySetResult(true);
}
catch (Exception e) { innerTcs.TrySetException(e); }
var tcs = new TaskCompletionSource<bool>(this);
BeginConnect(addresses, port, iar =>
{
- var innerTcs = (TaskCompletionSource<bool>)iar.AsyncState;
+ var innerTcs = (TaskCompletionSource<bool>)iar.AsyncState!;
try
{
- ((Socket)innerTcs.Task.AsyncState).EndConnect(iar);
+ ((Socket)innerTcs.Task.AsyncState!).EndConnect(iar);
innerTcs.TrySetResult(true);
}
catch (Exception e) { innerTcs.TrySetException(e); }
var tcs = new TaskCompletionSource<bool>(this);
BeginConnect(host, port, iar =>
{
- var innerTcs = (TaskCompletionSource<bool>)iar.AsyncState;
+ var innerTcs = (TaskCompletionSource<bool>)iar.AsyncState!;
try
{
- ((Socket)innerTcs.Task.AsyncState).EndConnect(iar);
+ ((Socket)innerTcs.Task.AsyncState!).EndConnect(iar);
innerTcs.TrySetResult(true);
}
catch (Exception e) { innerTcs.TrySetException(e); }
{
// We were able to extract the underlying byte[] from the Memory<byte>. Use it.
var tcs = new TaskCompletionSource<int>(this);
- BeginReceive(bufferArray.Array, bufferArray.Offset, bufferArray.Count, socketFlags, iar =>
+ BeginReceive(bufferArray.Array!, bufferArray.Offset, bufferArray.Count, socketFlags, iar =>
{
- var innerTcs = (TaskCompletionSource<int>)iar.AsyncState;
- try { innerTcs.TrySetResult(((Socket)innerTcs.Task.AsyncState).EndReceive(iar)); }
+ var innerTcs = (TaskCompletionSource<int>)iar.AsyncState!;
+ try { innerTcs.TrySetResult(((Socket)innerTcs.Task.AsyncState!).EndReceive(iar)); }
catch (Exception e) { innerTcs.TrySetException(e); }
}, tcs);
return tcs.Task;
var tcs = new TaskCompletionSource<int>(this);
BeginReceive(poolArray, 0, buffer.Length, socketFlags, iar =>
{
- var state = (Tuple<TaskCompletionSource<int>, Memory<byte>, byte[]>)iar.AsyncState;
+ var state = (Tuple<TaskCompletionSource<int>, Memory<byte>, byte[]>)iar.AsyncState!;
try
{
- int bytesCopied = ((Socket)state.Item1.Task.AsyncState).EndReceive(iar);
+ int bytesCopied = ((Socket)state.Item1.Task.AsyncState!).EndReceive(iar);
new ReadOnlyMemory<byte>(state.Item3, 0, bytesCopied).Span.CopyTo(state.Item2.Span);
state.Item1.TrySetResult(bytesCopied);
}
// Validate the arguments.
ValidateBuffersList(buffers);
- Int32TaskSocketAsyncEventArgs saea = RentSocketAsyncEventArgs(isReceive: true);
+ Int32TaskSocketAsyncEventArgs? saea = RentSocketAsyncEventArgs(isReceive: true);
if (saea != null)
{
// We got a cached instance. Configure the buffer list and initate the operation.
var tcs = new TaskCompletionSource<int>(this);
BeginReceive(buffers, socketFlags, iar =>
{
- var innerTcs = (TaskCompletionSource<int>)iar.AsyncState;
- try { innerTcs.TrySetResult(((Socket)innerTcs.Task.AsyncState).EndReceive(iar)); }
+ var innerTcs = (TaskCompletionSource<int>)iar.AsyncState!;
+ try { innerTcs.TrySetResult(((Socket)innerTcs.Task.AsyncState!).EndReceive(iar)); }
catch (Exception e) { innerTcs.TrySetException(e); }
}, tcs);
return tcs.Task;
internal Task<SocketReceiveFromResult> ReceiveFromAsync(ArraySegment<byte> buffer, SocketFlags socketFlags, EndPoint remoteEndPoint)
{
var tcs = new StateTaskCompletionSource<EndPoint, SocketReceiveFromResult>(this) { _field1 = remoteEndPoint };
- BeginReceiveFrom(buffer.Array, buffer.Offset, buffer.Count, socketFlags, ref tcs._field1, iar =>
+ BeginReceiveFrom(buffer.Array!, buffer.Offset, buffer.Count, socketFlags, ref tcs._field1, iar =>
{
- var innerTcs = (StateTaskCompletionSource<EndPoint, SocketReceiveFromResult>)iar.AsyncState;
+ var innerTcs = (StateTaskCompletionSource<EndPoint, SocketReceiveFromResult>)iar.AsyncState!;
try
{
- int receivedBytes = ((Socket)innerTcs.Task.AsyncState).EndReceiveFrom(iar, ref innerTcs._field1);
+ int receivedBytes = ((Socket)innerTcs.Task.AsyncState!).EndReceiveFrom(iar, ref innerTcs._field1);
innerTcs.TrySetResult(new SocketReceiveFromResult
{
ReceivedBytes = receivedBytes,
internal Task<SocketReceiveMessageFromResult> ReceiveMessageFromAsync(ArraySegment<byte> buffer, SocketFlags socketFlags, EndPoint remoteEndPoint)
{
var tcs = new StateTaskCompletionSource<SocketFlags, EndPoint, SocketReceiveMessageFromResult>(this) { _field1 = socketFlags, _field2 = remoteEndPoint };
- BeginReceiveMessageFrom(buffer.Array, buffer.Offset, buffer.Count, socketFlags, ref tcs._field2, iar =>
+ BeginReceiveMessageFrom(buffer.Array!, buffer.Offset, buffer.Count, socketFlags, ref tcs._field2, iar =>
{
- var innerTcs = (StateTaskCompletionSource<SocketFlags, EndPoint, SocketReceiveMessageFromResult>)iar.AsyncState;
+ var innerTcs = (StateTaskCompletionSource<SocketFlags, EndPoint, SocketReceiveMessageFromResult>)iar.AsyncState!;
try
{
IPPacketInformation ipPacketInformation;
- int receivedBytes = ((Socket)innerTcs.Task.AsyncState).EndReceiveMessageFrom(iar, ref innerTcs._field1, ref innerTcs._field2, out ipPacketInformation);
+ int receivedBytes = ((Socket)innerTcs.Task.AsyncState!).EndReceiveMessageFrom(iar, ref innerTcs._field1, ref innerTcs._field2, out ipPacketInformation);
innerTcs.TrySetResult(new SocketReceiveMessageFromResult
{
ReceivedBytes = receivedBytes,
if (MemoryMarshal.TryGetArray(buffer, out ArraySegment<byte> bufferArray))
{
var tcs = new TaskCompletionSource<int>(this);
- BeginSend(bufferArray.Array, bufferArray.Offset, bufferArray.Count, socketFlags, iar =>
+ BeginSend(bufferArray.Array!, bufferArray.Offset, bufferArray.Count, socketFlags, iar =>
{
- var innerTcs = (TaskCompletionSource<int>)iar.AsyncState;
- try { innerTcs.TrySetResult(((Socket)innerTcs.Task.AsyncState).EndSend(iar)); }
+ var innerTcs = (TaskCompletionSource<int>)iar.AsyncState!;
+ try { innerTcs.TrySetResult(((Socket)innerTcs.Task.AsyncState!).EndSend(iar)); }
catch (Exception e) { innerTcs.TrySetException(e); }
}, tcs);
return tcs.Task;
var tcs = new TaskCompletionSource<int>(this);
BeginSend(poolArray, 0, buffer.Length, socketFlags, iar =>
{
- var state = (Tuple<TaskCompletionSource<int>, byte[]>)iar.AsyncState;
+ var state = (Tuple<TaskCompletionSource<int>, byte[]>)iar.AsyncState!;
try
{
- state.Item1.TrySetResult(((Socket)state.Item1.Task.AsyncState).EndSend(iar));
+ state.Item1.TrySetResult(((Socket)state.Item1.Task.AsyncState!).EndSend(iar));
}
catch (Exception e)
{
// Validate the arguments.
ValidateBuffersList(buffers);
- Int32TaskSocketAsyncEventArgs saea = RentSocketAsyncEventArgs(isReceive: false);
+ Int32TaskSocketAsyncEventArgs? saea = RentSocketAsyncEventArgs(isReceive: false);
if (saea != null)
{
// We got a cached instance. Configure the buffer list and initate the operation.
var tcs = new TaskCompletionSource<int>(this);
BeginSend(buffers, socketFlags, iar =>
{
- var innerTcs = (TaskCompletionSource<int>)iar.AsyncState;
- try { innerTcs.TrySetResult(((Socket)innerTcs.Task.AsyncState).EndSend(iar)); }
+ var innerTcs = (TaskCompletionSource<int>)iar.AsyncState!;
+ try { innerTcs.TrySetResult(((Socket)innerTcs.Task.AsyncState!).EndSend(iar)); }
catch (Exception e) { innerTcs.TrySetException(e); }
}, tcs);
return tcs.Task;
internal Task<int> SendToAsync(ArraySegment<byte> buffer, SocketFlags socketFlags, EndPoint remoteEP)
{
var tcs = new TaskCompletionSource<int>(this);
- BeginSendTo(buffer.Array, buffer.Offset, buffer.Count, socketFlags, remoteEP, iar =>
+ BeginSendTo(buffer.Array!, buffer.Offset, buffer.Count, socketFlags, remoteEP, iar =>
{
- var innerTcs = (TaskCompletionSource<int>)iar.AsyncState;
- try { innerTcs.TrySetResult(((Socket)innerTcs.Task.AsyncState).EndSendTo(iar)); }
+ var innerTcs = (TaskCompletionSource<int>)iar.AsyncState!;
+ try { innerTcs.TrySetResult(((Socket)innerTcs.Task.AsyncState!).EndSendTo(iar)); }
catch (Exception e) { innerTcs.TrySetException(e); }
}, tcs);
return tcs.Task;
{
// Pull the relevant state off of the SAEA
SocketError error = saea.SocketError;
- Socket acceptSocket = saea.AcceptSocket;
+ Socket? acceptSocket = saea.AcceptSocket;
// Synchronize with the initiating thread. If the synchronous caller already got what
// it needs from the SAEA, then we can return it to the pool now. Otherwise, it'll be
// Complete the builder/task with the results.
if (error == SocketError.Success)
{
- builder.SetResult(acceptSocket);
+ builder.SetResult(acceptSocket!);
}
else
{
/// <summary>Rents a <see cref="Int32TaskSocketAsyncEventArgs"/> for immediate use.</summary>
/// <param name="isReceive">true if this instance will be used for a receive; false if for sends.</param>
- private Int32TaskSocketAsyncEventArgs RentSocketAsyncEventArgs(bool isReceive)
+ private Int32TaskSocketAsyncEventArgs? RentSocketAsyncEventArgs(bool isReceive)
{
// Get any cached SocketAsyncEventArg we may have.
CachedEventArgs cea = EventArgs;
- Int32TaskSocketAsyncEventArgs saea = isReceive ?
+ Int32TaskSocketAsyncEventArgs? saea = isReceive ?
Interlocked.Exchange(ref cea.TaskReceive, s_rentedInt32Sentinel) :
Interlocked.Exchange(ref cea.TaskSend, s_rentedInt32Sentinel);
/// <summary>Dispose of any cached <see cref="Int32TaskSocketAsyncEventArgs"/> instances.</summary>
private void DisposeCachedTaskSocketAsyncEventArgs()
{
- CachedEventArgs cea = _cachedTaskEventArgs;
+ CachedEventArgs? cea = _cachedTaskEventArgs;
if (cea != null)
{
Interlocked.Exchange(ref cea.TaskAccept, s_rentedSocketSentinel)?.Dispose();
/// <summary>A TaskCompletionSource that carries an extra field of strongly-typed state.</summary>
private class StateTaskCompletionSource<TField1, TResult> : TaskCompletionSource<TResult>
{
- internal TField1 _field1;
+ internal TField1 _field1 = default!; // always set on construction
public StateTaskCompletionSource(object baseState) : base(baseState) { }
}
/// <summary>A TaskCompletionSource that carries several extra fields of strongly-typed state.</summary>
private class StateTaskCompletionSource<TField1, TField2, TResult> : StateTaskCompletionSource<TField1, TResult>
{
- internal TField2 _field2;
+ internal TField2 _field2 = default!; // always set on construction
public StateTaskCompletionSource(object baseState) : base(baseState) { }
}
private sealed class CachedEventArgs
{
/// <summary>Cached instance for accept operations.</summary>
- public TaskSocketAsyncEventArgs<Socket> TaskAccept;
+ public TaskSocketAsyncEventArgs<Socket>? TaskAccept;
/// <summary>Cached instance for receive operations that return <see cref="Task{Int32}"/>.</summary>
- public Int32TaskSocketAsyncEventArgs TaskReceive;
+ public Int32TaskSocketAsyncEventArgs? TaskReceive;
/// <summary>Cached instance for send operations that return <see cref="Task{Int32}"/>.</summary>
- public Int32TaskSocketAsyncEventArgs TaskSend;
+ public Int32TaskSocketAsyncEventArgs? TaskSend;
/// <summary>Cached instance for receive operations that return <see cref="ValueTask{Int32}"/>.</summary>
- public AwaitableSocketAsyncEventArgs ValueTaskReceive;
+ public AwaitableSocketAsyncEventArgs? ValueTaskReceive;
/// <summary>Cached instance for send operations that return <see cref="ValueTask{Int32}"/>.</summary>
- public AwaitableSocketAsyncEventArgs ValueTaskSend;
+ public AwaitableSocketAsyncEventArgs? ValueTaskSend;
}
/// <summary>A SocketAsyncEventArgs with an associated async method builder.</summary>
{
internal static readonly AwaitableSocketAsyncEventArgs Reserved = new AwaitableSocketAsyncEventArgs() { _continuation = null };
/// <summary>Sentinel object used to indicate that the operation has completed prior to OnCompleted being called.</summary>
- private static readonly Action<object> s_completedSentinel = new Action<object>(state => throw new InvalidOperationException(SR.Format(SR.net_sockets_valuetaskmisuse, nameof(s_completedSentinel))));
+ private static readonly Action<object?> s_completedSentinel = new Action<object?>(state => throw new InvalidOperationException(SR.Format(SR.net_sockets_valuetaskmisuse, nameof(s_completedSentinel))));
/// <summary>Sentinel object used to indicate that the instance is available for use.</summary>
- private static readonly Action<object> s_availableSentinel = new Action<object>(state => throw new InvalidOperationException(SR.Format(SR.net_sockets_valuetaskmisuse, nameof(s_availableSentinel))));
+ private static readonly Action<object?> s_availableSentinel = new Action<object?>(state => throw new InvalidOperationException(SR.Format(SR.net_sockets_valuetaskmisuse, nameof(s_availableSentinel))));
/// <summary>
/// <see cref="s_availableSentinel"/> if the object is available for use, after GetResult has been called on a previous use.
/// null if the operation has not completed.
/// Another delegate if OnCompleted was called before the operation could complete, in which case it's the delegate to invoke
/// when the operation does complete.
/// </summary>
- private Action<object> _continuation = s_availableSentinel;
- private ExecutionContext _executionContext;
- private object _scheduler;
+ private Action<object?>? _continuation = s_availableSentinel;
+ private ExecutionContext? _executionContext;
+ private object? _scheduler;
/// <summary>Current token value given to a ValueTask and then verified against the value it passes back to us.</summary>
/// <remarks>
/// This is not meant to be a completely reliable mechanism, doesn't require additional synchronization, etc.
{
// When the operation completes, see if OnCompleted was already called to hook up a continuation.
// If it was, invoke the continuation.
- Action<object> c = _continuation;
+ Action<object?>? c = _continuation;
if (c != null || (c = Interlocked.CompareExchange(ref _continuation, s_completedSentinel, null)) != null)
{
Debug.Assert(c != s_availableSentinel, "The delegate should not have been the available sentinel.");
Debug.Assert(c != s_completedSentinel, "The delegate should not have been the completed sentinel.");
- object continuationState = UserToken;
+ object? continuationState = UserToken;
UserToken = null;
_continuation = s_completedSentinel; // in case someone's polling IsCompleted
- ExecutionContext ec = _executionContext;
+ ExecutionContext? ec = _executionContext;
if (ec == null)
{
InvokeContinuation(c, continuationState, forceAsync: false, requiresExecutionContextFlow: false);
_executionContext = null;
ExecutionContext.Run(ec, runState =>
{
- var t = (Tuple<AwaitableSocketAsyncEventArgs, Action<object>, object>)runState;
+ var t = (Tuple<AwaitableSocketAsyncEventArgs, Action<object?>, object>)runState!;
t.Item1.InvokeContinuation(t.Item2, t.Item3, forceAsync: false, requiresExecutionContextFlow: false);
}, Tuple.Create(this, c, continuationState));
}
}
/// <summary>Queues the provided continuation to be executed once the operation has completed.</summary>
- public void OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags)
+ public void OnCompleted(Action<object?> continuation, object? state, short token, ValueTaskSourceOnCompletedFlags flags)
{
if (token != _token)
{
if ((flags & ValueTaskSourceOnCompletedFlags.UseSchedulingContext) != 0)
{
- SynchronizationContext sc = SynchronizationContext.Current;
+ SynchronizationContext? sc = SynchronizationContext.Current;
if (sc != null && sc.GetType() != typeof(SynchronizationContext))
{
_scheduler = sc;
}
UserToken = state; // Use UserToken to carry the continuation state around
- Action<object> prevContinuation = Interlocked.CompareExchange(ref _continuation, continuation, null);
+ Action<object>? prevContinuation = Interlocked.CompareExchange(ref _continuation, continuation, null);
if (ReferenceEquals(prevContinuation, s_completedSentinel))
{
// Lost the race condition and the operation has now already completed.
}
}
- private void InvokeContinuation(Action<object> continuation, object state, bool forceAsync, bool requiresExecutionContextFlow)
+ private void InvokeContinuation(Action<object?> continuation, object? state, bool forceAsync, bool requiresExecutionContextFlow)
{
- object scheduler = _scheduler;
+ object? scheduler = _scheduler;
_scheduler = null;
if (scheduler != null)
{
sc.Post(s =>
{
- var t = (Tuple<Action<object>, object>)s;
+ var t = (Tuple<Action<object>, object>)s!;
t.Item1(t.Item2);
}, Tuple.Create(continuation, state));
}
bool broadcast = false, dontFragment = false, noDelay = false;
int receiveSize = -1, receiveTimeout = -1, sendSize = -1, sendTimeout = -1;
short ttl = -1;
- LingerOption linger = null;
+ LingerOption? linger = null;
if (_handle.IsTrackedOption(TrackedSocketOptions.DontFragment)) dontFragment = DontFragment;
if (_handle.IsTrackedOption(TrackedSocketOptions.EnableBroadcast)) broadcast = EnableBroadcast;
if (_handle.IsTrackedOption(TrackedSocketOptions.LingerState)) linger = LingerState;
if (_handle.IsTrackedOption(TrackedSocketOptions.DualMode)) DualMode = _handle.DualMode;
if (_handle.IsTrackedOption(TrackedSocketOptions.DontFragment)) DontFragment = dontFragment;
if (_handle.IsTrackedOption(TrackedSocketOptions.EnableBroadcast)) EnableBroadcast = broadcast;
- if (_handle.IsTrackedOption(TrackedSocketOptions.LingerState)) LingerState = linger;
+ if (_handle.IsTrackedOption(TrackedSocketOptions.LingerState)) LingerState = linger!;
if (_handle.IsTrackedOption(TrackedSocketOptions.NoDelay)) NoDelay = noDelay;
if (_handle.IsTrackedOption(TrackedSocketOptions.ReceiveBufferSize)) ReceiveBufferSize = receiveSize;
if (_handle.IsTrackedOption(TrackedSocketOptions.ReceiveTimeout)) ReceiveTimeout = receiveTimeout;
throw new PlatformNotSupportedException(SR.net_sockets_connect_multiconnect_notsupported);
}
- private Socket GetOrCreateAcceptSocket(Socket acceptSocket, bool unused, string propertyName, out SafeSocketHandle handle)
+ private Socket? GetOrCreateAcceptSocket(Socket? acceptSocket, bool unused, string propertyName, out SafeSocketHandle? handle)
{
// AcceptSocket is not supported on Unix.
if (acceptSocket != null)
}
}
- private void SendFileInternal(string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags)
+ private void SendFileInternal(string? fileName, byte[]? preBuffer, byte[]? postBuffer, TransmitFileOptions flags)
{
CheckTransmitFileOptions(flags);
// Open the file, if any
// Open it before we send the preBuffer so that any exception happens first
- FileStream fileStream = OpenFile(fileName);
+ FileStream? fileStream = OpenFile(fileName);
SocketError errorCode = SocketError.Success;
using (fileStream)
}
}
- private async Task SendFileInternalAsync(FileStream fileStream, byte[] preBuffer, byte[] postBuffer)
+ private async Task SendFileInternalAsync(FileStream? fileStream, byte[]? preBuffer, byte[]? postBuffer)
{
SocketError errorCode = SocketError.Success;
using (fileStream)
}
}
- private IAsyncResult BeginSendFileInternal(string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags, AsyncCallback callback, object state)
+ private IAsyncResult BeginSendFileInternal(string? fileName, byte[]? preBuffer, byte[]? postBuffer, TransmitFileOptions flags, AsyncCallback? callback, object? state)
{
CheckTransmitFileOptions(flags);
// Open the file, if any
// Open it before we send the preBuffer so that any exception happens first
- FileStream fileStream = OpenFile(fileName);
+ FileStream? fileStream = OpenFile(fileName);
return TaskToApm.Begin(SendFileInternalAsync(fileStream, preBuffer, postBuffer), callback, state);
}
{
public partial class Socket
{
- private DynamicWinsockMethods _dynamicWinsockMethods;
+ private DynamicWinsockMethods? _dynamicWinsockMethods;
internal void ReplaceHandleIfNecessaryAfterFailedConnect() { /* nop on Windows */ }
if (errorCode != SocketError.Success)
{
Debug.Assert(_handle.IsInvalid);
- _handle = null;
+ _handle = null!;
if (errorCode == SocketError.InvalidArgument)
{
if (_addressFamily != AddressFamily.InterNetwork && _addressFamily != AddressFamily.InterNetworkV6)
{
_handle.Dispose();
- _handle = null;
+ _handle = null!;
throw new NotSupportedException(SR.net_invalidversion);
}
else
{
_handle.Dispose();
- _handle = null;
+ _handle = null!;
throw new SocketException((int)errorCode);
}
NativeOverlapped* overlapped)
{
EnsureDynamicWinsockMethods();
- AcceptExDelegate acceptEx = _dynamicWinsockMethods.GetDelegate<AcceptExDelegate>(listenSocketHandle);
+ AcceptExDelegate acceptEx = _dynamicWinsockMethods!.GetDelegate<AcceptExDelegate>(listenSocketHandle);
return acceptEx(listenSocketHandle,
acceptSocketHandle,
out int remoteSocketAddressLength)
{
EnsureDynamicWinsockMethods();
- GetAcceptExSockaddrsDelegate getAcceptExSockaddrs = _dynamicWinsockMethods.GetDelegate<GetAcceptExSockaddrsDelegate>(_handle);
+ GetAcceptExSockaddrsDelegate getAcceptExSockaddrs = _dynamicWinsockMethods!.GetDelegate<GetAcceptExSockaddrsDelegate>(_handle);
getAcceptExSockaddrs(buffer,
receiveDataLength,
internal unsafe bool DisconnectEx(SafeSocketHandle socketHandle, NativeOverlapped* overlapped, int flags, int reserved)
{
EnsureDynamicWinsockMethods();
- DisconnectExDelegate disconnectEx = _dynamicWinsockMethods.GetDelegate<DisconnectExDelegate>(socketHandle);
+ DisconnectExDelegate disconnectEx = _dynamicWinsockMethods!.GetDelegate<DisconnectExDelegate>(socketHandle);
return disconnectEx(socketHandle, overlapped, flags, reserved);
}
internal bool DisconnectExBlocking(SafeSocketHandle socketHandle, IntPtr overlapped, int flags, int reserved)
{
EnsureDynamicWinsockMethods();
- DisconnectExDelegateBlocking disconnectEx_Blocking = _dynamicWinsockMethods.GetDelegate<DisconnectExDelegateBlocking>(socketHandle);
+ DisconnectExDelegateBlocking disconnectEx_Blocking = _dynamicWinsockMethods!.GetDelegate<DisconnectExDelegateBlocking>(socketHandle);
return disconnectEx_Blocking(socketHandle, overlapped, flags, reserved);
}
NativeOverlapped* overlapped)
{
EnsureDynamicWinsockMethods();
- ConnectExDelegate connectEx = _dynamicWinsockMethods.GetDelegate<ConnectExDelegate>(socketHandle);
+ ConnectExDelegate connectEx = _dynamicWinsockMethods!.GetDelegate<ConnectExDelegate>(socketHandle);
return connectEx(socketHandle, socketAddress, socketAddressSize, buffer, dataLength, out bytesSent, overlapped);
}
internal unsafe SocketError WSARecvMsg(SafeSocketHandle socketHandle, IntPtr msg, out int bytesTransferred, NativeOverlapped* overlapped, IntPtr completionRoutine)
{
EnsureDynamicWinsockMethods();
- WSARecvMsgDelegate recvMsg = _dynamicWinsockMethods.GetDelegate<WSARecvMsgDelegate>(socketHandle);
+ WSARecvMsgDelegate recvMsg = _dynamicWinsockMethods!.GetDelegate<WSARecvMsgDelegate>(socketHandle);
return recvMsg(socketHandle, msg, out bytesTransferred, overlapped, completionRoutine);
}
internal SocketError WSARecvMsgBlocking(SafeSocketHandle socketHandle, IntPtr msg, out int bytesTransferred, IntPtr overlapped, IntPtr completionRoutine)
{
EnsureDynamicWinsockMethods();
- WSARecvMsgDelegateBlocking recvMsg_Blocking = _dynamicWinsockMethods.GetDelegate<WSARecvMsgDelegateBlocking>(_handle);
+ WSARecvMsgDelegateBlocking recvMsg_Blocking = _dynamicWinsockMethods!.GetDelegate<WSARecvMsgDelegateBlocking>(_handle);
return recvMsg_Blocking(socketHandle, msg, out bytesTransferred, overlapped, completionRoutine);
}
internal unsafe bool TransmitPackets(SafeSocketHandle socketHandle, IntPtr packetArray, int elementCount, int sendSize, NativeOverlapped* overlapped, TransmitFileOptions flags)
{
EnsureDynamicWinsockMethods();
- TransmitPacketsDelegate transmitPackets = _dynamicWinsockMethods.GetDelegate<TransmitPacketsDelegate>(socketHandle);
+ TransmitPacketsDelegate transmitPackets = _dynamicWinsockMethods!.GetDelegate<TransmitPacketsDelegate>(socketHandle);
return transmitPackets(socketHandle, packetArray, elementCount, sendSize, overlapped, flags);
}
- internal static void SocketListToFileDescriptorSet(IList socketList, Span<IntPtr> fileDescriptorSet, ref int refsAdded)
+ internal static void SocketListToFileDescriptorSet(IList? socketList, Span<IntPtr> fileDescriptorSet, ref int refsAdded)
{
int count;
if (socketList == null || (count = socketList.Count) == 0)
{
if (!(socketList[current] is Socket socket))
{
- throw new ArgumentException(SR.Format(SR.net_sockets_select, socketList[current].GetType().FullName, typeof(System.Net.Sockets.Socket).FullName), nameof(socketList));
+ throw new ArgumentException(SR.Format(SR.net_sockets_select, socketList[current]?.GetType().FullName, typeof(System.Net.Sockets.Socket).FullName), nameof(socketList));
}
bool success = false;
// Transform the list socketList such that the only sockets left are those
// with a file descriptor contained in the array "fileDescriptorArray".
- internal static void SelectFileDescriptor(IList socketList, Span<IntPtr> fileDescriptorSet, ref int refsAdded)
+ internal static void SelectFileDescriptor(IList? socketList, Span<IntPtr> fileDescriptorSet, ref int refsAdded)
{
// Walk the list in order.
//
{
for (int currentSocket = 0; currentSocket < count; currentSocket++)
{
- Socket socket = socketList[currentSocket] as Socket;
+ Socket? socket = socketList[currentSocket] as Socket;
+ Debug.Assert(socket != null);
// Look for the file descriptor in the array.
int currentFileDescriptor;
}
}
- private Socket GetOrCreateAcceptSocket(Socket acceptSocket, bool checkDisconnected, string propertyName, out SafeSocketHandle handle)
+ private Socket GetOrCreateAcceptSocket(Socket? acceptSocket, bool checkDisconnected, string propertyName, out SafeSocketHandle handle)
{
// If an acceptSocket isn't specified, then we need to create one.
if (acceptSocket == null)
return acceptSocket;
}
- private void SendFileInternal(string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags)
+ private void SendFileInternal(string? fileName, byte[]? preBuffer, byte[]? postBuffer, TransmitFileOptions flags)
{
// Open the file, if any
- FileStream fileStream = OpenFile(fileName);
+ FileStream? fileStream = OpenFile(fileName);
SocketError errorCode;
using (fileStream)
{
- SafeFileHandle fileHandle = fileStream?.SafeFileHandle;
+ SafeFileHandle? fileHandle = fileStream?.SafeFileHandle;
// This can throw ObjectDisposedException.
errorCode = SocketPal.SendFile(_handle, fileHandle, preBuffer, postBuffer, flags);
}
}
- private IAsyncResult BeginSendFileInternal(string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags, AsyncCallback callback, object state)
+ private IAsyncResult BeginSendFileInternal(string? fileName, byte[]? preBuffer, byte[]? postBuffer, TransmitFileOptions flags, AsyncCallback? callback, object? state)
{
- FileStream fileStream = OpenFile(fileName);
+ FileStream? fileStream = OpenFile(fileName);
TransmitFileAsyncResult asyncResult = new TransmitFileAsyncResult(this, state, callback);
asyncResult.StartPostingAsyncOp(false);
private void EndSendFileInternal(IAsyncResult asyncResult)
{
- TransmitFileAsyncResult castedAsyncResult = asyncResult as TransmitFileAsyncResult;
+ TransmitFileAsyncResult? castedAsyncResult = asyncResult as TransmitFileAsyncResult;
if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this)
{
throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Net.Internals;
// _rightEndPoint is null if the socket has not been bound. Otherwise, it is any EndPoint of the
// correct type (IPEndPoint, etc).
- internal EndPoint _rightEndPoint;
- internal EndPoint _remoteEndPoint;
+ internal EndPoint? _rightEndPoint;
+ internal EndPoint? _remoteEndPoint;
// These flags monitor if the socket was ever connected at any time and if it still is.
private bool _isConnected;
// Keep track of the kind of endpoint used to do a non-blocking connect, so we can set
// it to _rightEndPoint when we discover we're connected.
- private EndPoint _nonBlockingConnectRightEndPoint;
+ private EndPoint? _nonBlockingConnectRightEndPoint;
// These are constants initialized by constructor.
private AddressFamily _addressFamily;
private ProtocolType _protocolType;
// These caches are one degree off of Socket since they're not used in the sync case/when disabled in config.
- private CacheSet _caches;
+ private CacheSet? _caches;
private class CacheSet
{
- internal CallbackClosure ConnectClosureCache;
- internal CallbackClosure AcceptClosureCache;
- internal CallbackClosure SendClosureCache;
- internal CallbackClosure ReceiveClosureCache;
+ internal CallbackClosure? ConnectClosureCache;
+ internal CallbackClosure? AcceptClosureCache;
+ internal CallbackClosure? SendClosureCache;
+ internal CallbackClosure? ReceiveClosureCache;
}
// Bool marked true if the native socket option IP_PKTINFO or IPV6_PKTINFO has been set.
private bool _receivingPacketInformation;
- private static object s_internalSyncObject;
+ private static object? s_internalSyncObject;
private int _closeTimeout = Socket.DefaultCloseTimeout;
private int _disposed; // 0 == false, anything else == true
}
// Gets the local end point.
- public EndPoint LocalEndPoint
+ public EndPoint? LocalEndPoint
{
get
{
}
// Gets the remote end point.
- public EndPoint RemoteEndPoint
+ public EndPoint? RemoteEndPoint
{
get
{
{
get
{
- return (int)GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ExclusiveAddressUse) != 0 ? true : false;
+ return (int)GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ExclusiveAddressUse)! != 0 ? true : false;
}
set
{
{
get
{
- return (int)GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer);
+ return (int)GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer)!;
}
set
{
{
get
{
- return (int)GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer);
+ return (int)GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer)!;
}
set
{
get
{
- return (int)GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout);
+ return (int)GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout)!;
}
set
{
{
get
{
- return (int)GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout);
+ return (int)GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout)!;
}
set
}
}
- public LingerOption LingerState
+ [DisallowNull]
+ public LingerOption? LingerState
{
get
{
- return (LingerOption)GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger);
+ return (LingerOption?)GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger);
}
set
{
- SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, value);
+ SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, value!);
}
}
{
get
{
- return (int)GetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay) != 0 ? true : false;
+ return (int)GetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay)! != 0 ? true : false;
}
set
{
{
if (_addressFamily == AddressFamily.InterNetwork)
{
- return (short)(int)GetSocketOption(SocketOptionLevel.IP, SocketOptionName.IpTimeToLive);
+ return (short)(int)GetSocketOption(SocketOptionLevel.IP, SocketOptionName.IpTimeToLive)!;
}
else if (_addressFamily == AddressFamily.InterNetworkV6)
{
- return (short)(int)GetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IpTimeToLive);
+ return (short)(int)GetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IpTimeToLive)!;
}
else
{
{
if (_addressFamily == AddressFamily.InterNetwork)
{
- return (int)GetSocketOption(SocketOptionLevel.IP, SocketOptionName.DontFragment) != 0 ? true : false;
+ return (int)GetSocketOption(SocketOptionLevel.IP, SocketOptionName.DontFragment)! != 0 ? true : false;
}
else
{
{
if (_addressFamily == AddressFamily.InterNetwork)
{
- return (int)GetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastLoopback) != 0 ? true : false;
+ return (int)GetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastLoopback)! != 0 ? true : false;
}
else if (_addressFamily == AddressFamily.InterNetworkV6)
{
- return (int)GetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.MulticastLoopback) != 0 ? true : false;
+ return (int)GetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.MulticastLoopback)! != 0 ? true : false;
}
else
{
{
get
{
- return (int)GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast) != 0 ? true : false;
+ return (int)GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast)! != 0 ? true : false;
}
set
{
{
throw new NotSupportedException(SR.net_invalidversion);
}
- return ((int)GetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only) == 0);
+ return ((int)GetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only)! == 0);
}
set
{
private void DoBind(EndPoint endPointSnapshot, Internals.SocketAddress socketAddress)
{
// Mitigation for Blue Screen of Death (Win7, maybe others).
- IPEndPoint ipEndPoint = endPointSnapshot as IPEndPoint;
+ IPEndPoint? ipEndPoint = endPointSnapshot as IPEndPoint;
if (!OSSupportsIPv4 && ipEndPoint != null && ipEndPoint.Address.IsIPv4MappedToIPv6)
{
UpdateStatusAfterSocketErrorAndThrowException(SocketError.InvalidArgument);
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"DST:{remoteEP}");
}
- DnsEndPoint dnsEP = remoteEP as DnsEndPoint;
+ DnsEndPoint? dnsEP = remoteEP as DnsEndPoint;
if (dnsEP != null)
{
ValidateForMultiConnect(isMultiEndpoint: true); // needs to come before CanTryAddressFamily call
// No need to call ValidateForMultiConnect(), as the validation
// will be handled by the delegated Connect overloads.
- IPAddress parsedAddress;
+ IPAddress? parsedAddress;
if (IPAddress.TryParse(host, out parsedAddress))
{
Connect(parsedAddress, port);
ValidateForMultiConnect(isMultiEndpoint: true); // needs to come before CanTryAddressFamily call
- ExceptionDispatchInfo lastex = null;
+ ExceptionDispatchInfo? lastex = null;
foreach (IPAddress address in addresses)
{
if (CanTryAddressFamily(address.AddressFamily))
Socket socket = CreateAcceptSocket(acceptedSocketHandle, _rightEndPoint.Create(socketAddress));
if (NetEventSource.IsEnabled)
{
- NetEventSource.Accepted(socket, socket.RemoteEndPoint, socket.LocalEndPoint);
+ NetEventSource.Accepted(socket, socket.RemoteEndPoint!, socket.LocalEndPoint);
NetEventSource.Exit(this, socket);
}
return socket;
SendFile(fileName, null, null, TransmitFileOptions.UseDefaultWorkerThread);
}
- public void SendFile(string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags)
+ public void SendFile(string? fileName, byte[]? preBuffer, byte[]? postBuffer, TransmitFileOptions flags)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
UpdateReceiveSocketErrorForDisposed(ref errorCode, bytesTransferred);
// If the native call fails we'll throw a SocketException.
- SocketException socketException = null;
+ SocketException? socketException = null;
if (errorCode != SocketError.Success)
{
socketException = new SocketException((int)errorCode);
return ReceiveFrom(buffer, 0, buffer != null ? buffer.Length : 0, SocketFlags.None, ref remoteEP);
}
- public int IOControl(int ioControlCode, byte[] optionInValue, byte[] optionOutValue)
+ public int IOControl(int ioControlCode, byte[]? optionInValue, byte[]? optionOutValue)
{
ThrowIfDisposed();
return realOptionLength;
}
- public int IOControl(IOControlCode ioControlCode, byte[] optionInValue, byte[] optionOutValue)
+ public int IOControl(IOControlCode ioControlCode, byte[]? optionInValue, byte[]? optionOutValue)
{
return IOControl(unchecked((int)ioControlCode), optionInValue, optionOutValue);
}
if (optionLevel == SocketOptionLevel.Socket && optionName == SocketOptionName.Linger)
{
- LingerOption lingerOption = optionValue as LingerOption;
+ LingerOption? lingerOption = optionValue as LingerOption;
if (lingerOption == null)
{
throw new ArgumentException(SR.Format(SR.net_sockets_invalid_optionValue, "LingerOption"), nameof(optionValue));
}
else if (optionLevel == SocketOptionLevel.IP && (optionName == SocketOptionName.AddMembership || optionName == SocketOptionName.DropMembership))
{
- MulticastOption multicastOption = optionValue as MulticastOption;
+ MulticastOption? multicastOption = optionValue as MulticastOption;
if (multicastOption == null)
{
throw new ArgumentException(SR.Format(SR.net_sockets_invalid_optionValue, "MulticastOption"), nameof(optionValue));
else if (optionLevel == SocketOptionLevel.IPv6 && (optionName == SocketOptionName.AddMembership || optionName == SocketOptionName.DropMembership))
{
// IPv6 Changes: Handle IPv6 Multicast Add / Drop
- IPv6MulticastOption multicastOption = optionValue as IPv6MulticastOption;
+ IPv6MulticastOption? multicastOption = optionValue as IPv6MulticastOption;
if (multicastOption == null)
{
throw new ArgumentException(SR.Format(SR.net_sockets_invalid_optionValue, "IPv6MulticastOption"), nameof(optionValue));
}
// Gets the value of a socket option.
- public object GetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName)
+ public object? GetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName)
{
ThrowIfDisposed();
if (optionLevel == SocketOptionLevel.Socket && optionName == SocketOptionName.Linger)
_handle,
optionLevel,
optionName,
- optionValue,
+ optionValue!,
ref optionLength);
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Interop.Winsock.getsockopt returns errorCode:{errorCode}");
}
// Determines the status of a socket.
- public static void Select(IList checkRead, IList checkWrite, IList checkError, int microSeconds)
+ public static void Select(IList? checkRead, IList? checkWrite, IList? checkError, int microSeconds)
{
// Validate input parameters.
if ((checkRead == null || checkRead.Count == 0) && (checkWrite == null || checkWrite.Count == 0) && (checkError == null || checkError.Count == 0))
// Return Value:
//
// IAsyncResult - Async result used to retrieve result
- public IAsyncResult BeginConnect(EndPoint remoteEP, AsyncCallback callback, object state)
+ public IAsyncResult BeginConnect(EndPoint remoteEP, AsyncCallback? callback, object? state)
{
// Validate input parameters.
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, remoteEP);
}
- DnsEndPoint dnsEP = remoteEP as DnsEndPoint;
+ DnsEndPoint? dnsEP = remoteEP as DnsEndPoint;
if (dnsEP != null)
{
ValidateForMultiConnect(isMultiEndpoint: true); // needs to come before CanTryAddressFamily call
- internal IAsyncResult UnsafeBeginConnect(EndPoint remoteEP, AsyncCallback callback, object state, bool flowContext = false)
+ internal IAsyncResult UnsafeBeginConnect(EndPoint remoteEP, AsyncCallback? callback, object? state, bool flowContext = false)
{
if (CanUseConnectEx(remoteEP))
{
return asyncResult;
}
- public IAsyncResult BeginConnect(string host, int port, AsyncCallback requestCallback, object state)
+ public IAsyncResult BeginConnect(string host, int port, AsyncCallback? requestCallback, object? state)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, host);
ThrowIfDisposed();
throw new SocketException((int)SocketError.IsConnected);
}
- IPAddress parsedAddress;
+ IPAddress? parsedAddress;
if (IPAddress.TryParse(host, out parsedAddress))
{
IAsyncResult r = BeginConnect(parsedAddress, port, requestCallback, state);
return result;
}
- public IAsyncResult BeginConnect(IPAddress address, int port, AsyncCallback requestCallback, object state)
+ public IAsyncResult BeginConnect(IPAddress address, int port, AsyncCallback? requestCallback, object? state)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, address);
ThrowIfDisposed();
return result;
}
- public IAsyncResult BeginConnect(IPAddress[] addresses, int port, AsyncCallback requestCallback, object state)
+ public IAsyncResult BeginConnect(IPAddress[] addresses, int port, AsyncCallback? requestCallback, object? state)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, addresses);
ThrowIfDisposed();
return result;
}
- public IAsyncResult BeginDisconnect(bool reuseSocket, AsyncCallback callback, object state)
+ public IAsyncResult BeginDisconnect(bool reuseSocket, AsyncCallback? callback, object? state)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
ThrowIfDisposed();
throw new ArgumentNullException(nameof(asyncResult));
}
- ContextAwareResult castedAsyncResult =
+ ContextAwareResult? castedAsyncResult =
asyncResult as ConnectOverlappedAsyncResult ??
asyncResult as MultipleAddressConnectAsyncResult ??
- (ContextAwareResult)(asyncResult as ConnectAsyncResult);
+ (ContextAwareResult?)(asyncResult as ConnectAsyncResult);
if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"asyncResult:{asyncResult}");
- Exception ex = castedAsyncResult.Result as Exception;
+ Exception? ex = castedAsyncResult.Result as Exception;
if (ex != null || (SocketError)castedAsyncResult.ErrorCode != SocketError.Success)
{
if (ex == null)
}
//get async result and check for errors
- LazyAsyncResult castedAsyncResult = asyncResult as LazyAsyncResult;
+ LazyAsyncResult? castedAsyncResult = asyncResult as LazyAsyncResult;
if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this)
{
throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
// Return Value:
//
// IAsyncResult - Async result used to retrieve result
- public IAsyncResult BeginSend(byte[] buffer, int offset, int size, SocketFlags socketFlags, AsyncCallback callback, object state)
+ public IAsyncResult BeginSend(byte[] buffer, int offset, int size, SocketFlags socketFlags, AsyncCallback? callback, object? state)
{
SocketError errorCode;
- IAsyncResult result = BeginSend(buffer, offset, size, socketFlags, out errorCode, callback, state);
+ IAsyncResult? result = BeginSend(buffer, offset, size, socketFlags, out errorCode, callback, state);
if (errorCode != SocketError.Success && errorCode != SocketError.IOPending)
{
throw new SocketException((int)errorCode);
}
- return result;
+ return result!;
}
- public IAsyncResult BeginSend(byte[] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback, object state)
+ public IAsyncResult? BeginSend(byte[] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback? callback, object? state)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
ThrowIfDisposed();
}
// We need to flow the context here. But we don't need to lock the context - we don't use it until the callback.
- OverlappedAsyncResult asyncResult = new OverlappedAsyncResult(this, state, callback);
+ OverlappedAsyncResult? asyncResult = new OverlappedAsyncResult(this, state, callback);
asyncResult.StartPostingAsyncOp(false);
// Run the send with this asyncResult.
return errorCode;
}
- public IAsyncResult BeginSend(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, AsyncCallback callback, object state)
+ public IAsyncResult BeginSend(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, AsyncCallback? callback, object? state)
{
SocketError errorCode;
- IAsyncResult result = BeginSend(buffers, socketFlags, out errorCode, callback, state);
+ IAsyncResult? result = BeginSend(buffers, socketFlags, out errorCode, callback, state);
if (errorCode != SocketError.Success && errorCode != SocketError.IOPending)
{
throw new SocketException((int)errorCode);
}
- return result;
+ return result!;
}
- public IAsyncResult BeginSend(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback, object state)
+ public IAsyncResult? BeginSend(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback? callback, object? state)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
ThrowIfDisposed();
}
// We need to flow the context here. But we don't need to lock the context - we don't use it until the callback.
- OverlappedAsyncResult asyncResult = new OverlappedAsyncResult(this, state, callback);
+ OverlappedAsyncResult? asyncResult = new OverlappedAsyncResult(this, state, callback);
asyncResult.StartPostingAsyncOp(false);
// Run the send with this asyncResult.
throw new ArgumentNullException(nameof(asyncResult));
}
- OverlappedAsyncResult castedAsyncResult = asyncResult as OverlappedAsyncResult;
+ OverlappedAsyncResult? castedAsyncResult = asyncResult as OverlappedAsyncResult;
if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this)
{
throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
return bytesTransferred;
}
- public IAsyncResult BeginSendFile(string fileName, AsyncCallback callback, object state)
+ public IAsyncResult BeginSendFile(string fileName, AsyncCallback? callback, object? state)
{
return BeginSendFile(fileName, null, null, TransmitFileOptions.UseDefaultWorkerThread, callback, state);
}
- public IAsyncResult BeginSendFile(string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags, AsyncCallback callback, object state)
+ public IAsyncResult BeginSendFile(string? fileName, byte[]? preBuffer, byte[]? postBuffer, TransmitFileOptions flags, AsyncCallback? callback, object? state)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
// Return Value:
//
// IAsyncResult - Async result used to retrieve result
- public IAsyncResult BeginSendTo(byte[] buffer, int offset, int size, SocketFlags socketFlags, EndPoint remoteEP, AsyncCallback callback, object state)
+ public IAsyncResult BeginSendTo(byte[] buffer, int offset, int size, SocketFlags socketFlags, EndPoint remoteEP, AsyncCallback? callback, object? state)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
ThrowIfDisposed();
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"size:{size}");
- EndPoint oldEndPoint = _rightEndPoint;
+ EndPoint? oldEndPoint = _rightEndPoint;
// Guarantee to call CheckAsyncCallOverlappedResult if we call SetUnamangedStructures with a cache in order to
// avoid a Socket leak in case of error.
throw new ArgumentNullException(nameof(asyncResult));
}
- OverlappedAsyncResult castedAsyncResult = asyncResult as OverlappedAsyncResult;
+ OverlappedAsyncResult? castedAsyncResult = asyncResult as OverlappedAsyncResult;
if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this)
{
throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
// Return Value:
//
// IAsyncResult - Async result used to retrieve result
- public IAsyncResult BeginReceive(byte[] buffer, int offset, int size, SocketFlags socketFlags, AsyncCallback callback, object state)
+ public IAsyncResult BeginReceive(byte[] buffer, int offset, int size, SocketFlags socketFlags, AsyncCallback? callback, object? state)
{
SocketError errorCode;
- IAsyncResult result = BeginReceive(buffer, offset, size, socketFlags, out errorCode, callback, state);
+ IAsyncResult? result = BeginReceive(buffer, offset, size, socketFlags, out errorCode, callback, state);
if (errorCode != SocketError.Success && errorCode != SocketError.IOPending)
{
throw new SocketException((int)errorCode);
}
- return result;
+ return result!;
}
- public IAsyncResult BeginReceive(byte[] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback, object state)
+ public IAsyncResult? BeginReceive(byte[] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback? callback, object? state)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
}
// We need to flow the context here. But we don't need to lock the context - we don't use it until the callback.
- OverlappedAsyncResult asyncResult = new OverlappedAsyncResult(this, state, callback);
+ OverlappedAsyncResult? asyncResult = new OverlappedAsyncResult(this, state, callback);
asyncResult.StartPostingAsyncOp(false);
// Run the receive with this asyncResult.
return errorCode;
}
- public IAsyncResult BeginReceive(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, AsyncCallback callback, object state)
+ public IAsyncResult BeginReceive(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, AsyncCallback? callback, object? state)
{
SocketError errorCode;
- IAsyncResult result = BeginReceive(buffers, socketFlags, out errorCode, callback, state);
+ IAsyncResult? result = BeginReceive(buffers, socketFlags, out errorCode, callback, state);
if (errorCode != SocketError.Success && errorCode != SocketError.IOPending)
{
throw new SocketException((int)errorCode);
}
- return result;
+ return result!;
}
- public IAsyncResult BeginReceive(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback, object state)
+ public IAsyncResult? BeginReceive(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback? callback, object? state)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
}
// We need to flow the context here. But we don't need to lock the context - we don't use it until the callback.
- OverlappedAsyncResult asyncResult = new OverlappedAsyncResult(this, state, callback);
+ OverlappedAsyncResult? asyncResult = new OverlappedAsyncResult(this, state, callback);
asyncResult.StartPostingAsyncOp(false);
// Run the receive with this asyncResult.
throw new ArgumentNullException(nameof(asyncResult));
}
- OverlappedAsyncResult castedAsyncResult = asyncResult as OverlappedAsyncResult;
+ OverlappedAsyncResult? castedAsyncResult = asyncResult as OverlappedAsyncResult;
if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this)
{
throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
return bytesTransferred;
}
- public IAsyncResult BeginReceiveMessageFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP, AsyncCallback callback, object state)
+ public IAsyncResult BeginReceiveMessageFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP, AsyncCallback? callback, object? state)
{
if (NetEventSource.IsEnabled)
{
{
try
{
- remoteEP = remoteEP.Create(asyncResult.SocketAddress);
+ remoteEP = remoteEP.Create(asyncResult.SocketAddress!);
}
catch
{
throw new ArgumentNullException(nameof(asyncResult));
}
- ReceiveMessageOverlappedAsyncResult castedAsyncResult = asyncResult as ReceiveMessageOverlappedAsyncResult;
+ ReceiveMessageOverlappedAsyncResult? castedAsyncResult = asyncResult as ReceiveMessageOverlappedAsyncResult;
if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this)
{
throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
castedAsyncResult.EndCalled = true;
// Update socket address size.
- castedAsyncResult.SocketAddress.InternalSize = castedAsyncResult.GetSocketAddressSize();
+ castedAsyncResult.SocketAddress!.InternalSize = castedAsyncResult.GetSocketAddressSize();
if (!socketAddressOriginal.Equals(castedAsyncResult.SocketAddress))
{
// Return Value:
//
// IAsyncResult - Async result used to retrieve result
- public IAsyncResult BeginReceiveFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP, AsyncCallback callback, object state)
+ public IAsyncResult BeginReceiveFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP, AsyncCallback? callback, object? state)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
// Capture the context, maybe call the callback, and return.
asyncResult.FinishPostingAsyncOp(ref Caches.ReceiveClosureCache);
- if (asyncResult.CompletedSynchronously && !asyncResult.SocketAddressOriginal.Equals(asyncResult.SocketAddress))
+ if (asyncResult.CompletedSynchronously && !asyncResult.SocketAddressOriginal!.Equals(asyncResult.SocketAddress))
{
try
{
- remoteEP = remoteEP.Create(asyncResult.SocketAddress);
+ remoteEP = remoteEP.Create(asyncResult.SocketAddress!);
}
catch
{
private void DoBeginReceiveFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, EndPoint endPointSnapshot, Internals.SocketAddress socketAddress, OriginalAddressOverlappedAsyncResult asyncResult)
{
- EndPoint oldEndPoint = _rightEndPoint;
+ EndPoint? oldEndPoint = _rightEndPoint;
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"size:{size}");
throw new ArgumentNullException(nameof(asyncResult));
}
- OverlappedAsyncResult castedAsyncResult = asyncResult as OverlappedAsyncResult;
+ OverlappedAsyncResult? castedAsyncResult = asyncResult as OverlappedAsyncResult;
if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this)
{
throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
castedAsyncResult.EndCalled = true;
// Update socket address size.
- castedAsyncResult.SocketAddress.InternalSize = castedAsyncResult.GetSocketAddressSize();
+ castedAsyncResult.SocketAddress!.InternalSize = castedAsyncResult.GetSocketAddressSize();
if (!socketAddressOriginal.Equals(castedAsyncResult.SocketAddress))
{
// Return Value:
//
// IAsyncResult - Async result used to retrieve resultant new socket
- public IAsyncResult BeginAccept(AsyncCallback callback, object state)
+ public IAsyncResult BeginAccept(AsyncCallback? callback, object? state)
{
if (!_isDisconnected)
{
return null; // unreachable
}
- public IAsyncResult BeginAccept(int receiveSize, AsyncCallback callback, object state)
+ public IAsyncResult BeginAccept(int receiveSize, AsyncCallback? callback, object? state)
{
return BeginAccept(null, receiveSize, callback, state);
}
// This is the truly async version that uses AcceptEx.
- public IAsyncResult BeginAccept(Socket acceptSocket, int receiveSize, AsyncCallback callback, object state)
+ public IAsyncResult BeginAccept(Socket? acceptSocket, int receiveSize, AsyncCallback? callback, object? state)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
ThrowIfDisposed();
return asyncResult;
}
- private void DoBeginAccept(Socket acceptSocket, int receiveSize, AcceptOverlappedAsyncResult asyncResult)
+ private void DoBeginAccept(Socket? acceptSocket, int receiveSize, AcceptOverlappedAsyncResult asyncResult)
{
if (_rightEndPoint == null)
{
throw new InvalidOperationException(SR.net_sockets_mustlisten);
}
- SafeSocketHandle acceptHandle;
+ SafeSocketHandle? acceptHandle;
asyncResult.AcceptSocket = GetOrCreateAcceptSocket(acceptSocket, false, nameof(acceptSocket), out acceptHandle);
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"AcceptSocket:{acceptSocket}");
public Socket EndAccept(IAsyncResult asyncResult)
{
int bytesTransferred;
- byte[] buffer;
+ byte[]? buffer;
return EndAccept(out buffer, out bytesTransferred, asyncResult);
}
- public Socket EndAccept(out byte[] buffer, IAsyncResult asyncResult)
+ public Socket EndAccept(out byte[]? buffer, IAsyncResult asyncResult)
{
int bytesTransferred;
- byte[] innerBuffer;
+ byte[]? innerBuffer;
Socket socket = EndAccept(out innerBuffer, out bytesTransferred, asyncResult);
buffer = new byte[bytesTransferred];
- Buffer.BlockCopy(innerBuffer, 0, buffer, 0, bytesTransferred);
+ // https://github.com/dotnet/runtime/issues/32633 - this throws on Unix
+ Buffer.BlockCopy(innerBuffer!, 0, buffer, 0, bytesTransferred);
return socket;
}
- public Socket EndAccept(out byte[] buffer, out int bytesTransferred, IAsyncResult asyncResult)
+ public Socket EndAccept(out byte[]? buffer, out int bytesTransferred, IAsyncResult asyncResult)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, asyncResult);
ThrowIfDisposed();
{
throw new ArgumentNullException(nameof(asyncResult));
}
- AcceptOverlappedAsyncResult castedAsyncResult = asyncResult as AcceptOverlappedAsyncResult;
+ AcceptOverlappedAsyncResult? castedAsyncResult = asyncResult as AcceptOverlappedAsyncResult;
if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this)
{
throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndAccept"));
}
- Socket socket = (Socket)castedAsyncResult.InternalWaitForCompletion();
+ Socket socket = (Socket)castedAsyncResult.InternalWaitForCompletion()!;
bytesTransferred = (int)castedAsyncResult.BytesTransferred;
buffer = castedAsyncResult.Buffer;
}
// Handle AcceptSocket property.
- SafeSocketHandle acceptHandle;
+ SafeSocketHandle? acceptHandle;
e.AcceptSocket = GetOrCreateAcceptSocket(e.AcceptSocket, true, "AcceptSocket", out acceptHandle);
// Prepare for and make the native call.
}
// Prepare SocketAddress.
- EndPoint endPointSnapshot = e.RemoteEndPoint;
- DnsEndPoint dnsEP = endPointSnapshot as DnsEndPoint;
+ EndPoint? endPointSnapshot = e.RemoteEndPoint;
+ DnsEndPoint? dnsEP = endPointSnapshot as DnsEndPoint;
if (dnsEP != null)
{
WildcardBindForConnectIfNecessary(endPointSnapshot.AddressFamily);
// Save the old RightEndPoint and prep new RightEndPoint.
- EndPoint oldEndPoint = _rightEndPoint;
+ EndPoint? oldEndPoint = _rightEndPoint;
if (_rightEndPoint == null)
{
_rightEndPoint = endPointSnapshot;
}
EndPoint endPointSnapshot = e.RemoteEndPoint;
- DnsEndPoint dnsEP = endPointSnapshot as DnsEndPoint;
+ DnsEndPoint? dnsEP = endPointSnapshot as DnsEndPoint;
if (dnsEP != null)
{
- Socket attemptSocket = null;
- MultipleConnectAsync multipleConnectAsync = null;
+ Socket? attemptSocket = null;
+ MultipleConnectAsync? multipleConnectAsync = null;
if (dnsEP.AddressFamily == AddressFamily.Unspecified)
{
// This is the only *Connect* API that fully supports multiple endpoint attempts, as it's responsible
// Throw if socket disposed
ThrowIfDisposed();
+ if (e == null)
+ {
+ throw new ArgumentNullException(nameof(e));
+ }
+
// Prepare for and make the native call.
e.StartOperationCommon(this, SocketAsyncOperation.Disconnect);
SocketError socketError = SocketError.Success;
// Prepare for and make the native call.
e.StartOperationCommon(this, SocketAsyncOperation.SendTo);
- EndPoint oldEndPoint = _rightEndPoint;
+ EndPoint? oldEndPoint = _rightEndPoint;
if (_rightEndPoint == null)
{
_rightEndPoint = endPointSnapshot;
{
// DualMode: When bound to IPv6Any you must enable both socket options.
// When bound to an IPv4 mapped IPv6 address you must enable the IPv4 socket option.
- IPEndPoint ipEndPoint = _rightEndPoint as IPEndPoint;
- IPAddress boundAddress = (ipEndPoint != null ? ipEndPoint.Address : null);
+ IPEndPoint? ipEndPoint = _rightEndPoint as IPEndPoint;
+ IPAddress? boundAddress = (ipEndPoint != null ? ipEndPoint.Address : null);
Debug.Assert(boundAddress != null, "Not Bound");
if (_addressFamily == AddressFamily.InterNetwork)
{
}
}
- private LingerOption GetLingerOpt()
+ private LingerOption? GetLingerOpt()
{
- LingerOption lingerOption;
+ LingerOption? lingerOption;
SocketError errorCode = SocketPal.GetLingerOption(_handle, out lingerOption);
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Interop.Winsock.getsockopt returns errorCode:{errorCode}");
return lingerOption;
}
- private MulticastOption GetMulticastOpt(SocketOptionName optionName)
+ private MulticastOption? GetMulticastOpt(SocketOptionName optionName)
{
- MulticastOption multicastOption;
+ MulticastOption? multicastOption;
SocketError errorCode = SocketPal.GetMulticastOption(_handle, optionName, out multicastOption);
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Interop.Winsock.getsockopt returns errorCode:{errorCode}");
}
// IPv6 getsockopt for JOIN / LEAVE multicast group.
- private IPv6MulticastOption GetIPv6MulticastOpt(SocketOptionName optionName)
+ private IPv6MulticastOption? GetIPv6MulticastOpt(SocketOptionName optionName)
{
- IPv6MulticastOption multicastOption;
+ IPv6MulticastOption? multicastOption;
SocketError errorCode = SocketPal.GetIPv6MulticastOption(_handle, optionName, out multicastOption);
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Interop.Winsock.getsockopt returns errorCode:{errorCode}");
// Implements ConnectEx - this provides completion port IO and support for disconnect and reconnects.
// Since this is private, the unsafe mode is specified with a flag instead of an overload.
- private IAsyncResult BeginConnectEx(EndPoint remoteEP, bool flowContext, AsyncCallback callback, object state)
+ private IAsyncResult BeginConnectEx(EndPoint remoteEP, bool flowContext, AsyncCallback? callback, object? state)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
asyncResult.StartPostingAsyncOp(false);
}
- EndPoint oldEndPoint = _rightEndPoint;
+ EndPoint? oldEndPoint = _rightEndPoint;
if (_rightEndPoint == null)
{
_rightEndPoint = endPointSnapshot;
bool invokeCallback = false;
- MultipleAddressConnectAsyncResult context = (MultipleAddressConnectAsyncResult)result.AsyncState;
+ MultipleAddressConnectAsyncResult context = (MultipleAddressConnectAsyncResult)result.AsyncState!;
try
{
invokeCallback = DoDnsCallback(result, context);
{
private readonly EndPoint _endPoint;
- internal ConnectAsyncResult(object myObject, EndPoint endPoint, object myState, AsyncCallback myCallBack) :
+ internal ConnectAsyncResult(object myObject, EndPoint endPoint, object? myState, AsyncCallback? myCallBack) :
base(myObject, myState, myCallBack)
{
_endPoint = endPoint;
private sealed class MultipleAddressConnectAsyncResult : ContextAwareResult
{
- internal MultipleAddressConnectAsyncResult(IPAddress[] addresses, int port, Socket socket, object myState, AsyncCallback myCallBack) :
+ internal MultipleAddressConnectAsyncResult(IPAddress[]? addresses, int port, Socket socket, object? myState, AsyncCallback? myCallBack) :
base(socket, myState, myCallBack)
{
_addresses = addresses;
}
internal Socket _socket; // Keep this member just to avoid all the casting.
- internal IPAddress[] _addresses;
+ internal IPAddress[]? _addresses;
internal int _index;
internal int _port;
- internal Exception _lastException;
+ internal Exception? _lastException;
- internal override EndPoint RemoteEndPoint
+ internal override EndPoint? RemoteEndPoint
{
get
{
}
}
- private static AsyncCallback s_multipleAddressConnectCallback;
+ private static AsyncCallback? s_multipleAddressConnectCallback;
private static AsyncCallback CachedMultipleAddressConnectCallback
{
get
}
}
- private static object PostOneBeginConnect(MultipleAddressConnectAsyncResult context)
+ private static object? PostOneBeginConnect(MultipleAddressConnectAsyncResult context)
{
- IPAddress currentAddressSnapshot = context._addresses[context._index];
+ IPAddress currentAddressSnapshot = context._addresses![context._index];
context._socket.ReplaceHandleIfNecessaryAfterFailedConnect();
bool invokeCallback = false;
- MultipleAddressConnectAsyncResult context = (MultipleAddressConnectAsyncResult)result.AsyncState;
+ MultipleAddressConnectAsyncResult context = (MultipleAddressConnectAsyncResult)result.AsyncState!;
try
{
invokeCallback = DoMultipleAddressConnectCallback(result, context);
// This is like a regular async callback worker, except the result can be an exception. This is a useful pattern when
// processing should continue whether or not an async step failed.
- private static bool DoMultipleAddressConnectCallback(object result, MultipleAddressConnectAsyncResult context)
+ private static bool DoMultipleAddressConnectCallback(object? result, MultipleAddressConnectAsyncResult context)
{
while (result != null)
{
- Exception ex = result as Exception;
+ Exception? ex = result as Exception;
if (ex == null)
{
try
}
else
{
- if (++context._index >= context._addresses.Length)
+ if (++context._index >= context._addresses!.Length)
{
ExceptionDispatchInfo.Throw(ex);
}
}
}
- private void UpdateStatusAfterSocketErrorAndThrowException(SocketError error, [CallerMemberName] string callerName = null)
+ private void UpdateStatusAfterSocketErrorAndThrowException(SocketError error, [CallerMemberName] string? callerName = null)
{
// Update the internal state of this socket according to the error before throwing.
var socketException = new SocketException((int)error);
partial void ValidateForMultiConnect(bool isMultiEndpoint);
// Helper for SendFile implementations
- private static FileStream OpenFile(string name) => string.IsNullOrEmpty(name) ? null : File.OpenRead(name);
+ private static FileStream? OpenFile(string? name) => string.IsNullOrEmpty(name) ? null : File.OpenRead(name);
private void UpdateReceiveSocketErrorForDisposed(ref SocketError socketError, int bytesTransferred)
{
}
}
+ [DoesNotReturn]
private void ThrowObjectDisposedException() => throw new ObjectDisposedException(GetType().FullName);
private bool IsConnectionOriented => _socketType == SocketType.Stream;
- internal static void SocketListDangerousReleaseRefs(IList socketList, ref int refsAdded)
+ internal static void SocketListDangerousReleaseRefs(IList? socketList, ref int refsAdded)
{
if (socketList == null)
{
for (int i = 0; (i < socketList.Count) && (refsAdded > 0); i++)
{
- Socket socket = (Socket)socketList[i];
+ Socket socket = (Socket)socketList[i]!;
socket.InternalSafeHandle.DangerousRelease();
refsAdded--;
}
// refactoring, these could also potentially be moved to SocketAsyncEventArgs, which
// would be more invasive but which would allow them to be reused across socket instances
// and also eliminate the interlocked necessary to rent the instances.
- private AcceptOperation _cachedAcceptOperation;
- private BufferMemoryReceiveOperation _cachedBufferMemoryReceiveOperation;
- private BufferListReceiveOperation _cachedBufferListReceiveOperation;
- private BufferMemorySendOperation _cachedBufferMemorySendOperation;
- private BufferListSendOperation _cachedBufferListSendOperation;
+ private AcceptOperation? _cachedAcceptOperation;
+ private BufferMemoryReceiveOperation? _cachedBufferMemoryReceiveOperation;
+ private BufferListReceiveOperation? _cachedBufferListReceiveOperation;
+ private BufferMemorySendOperation? _cachedBufferMemorySendOperation;
+ private BufferListSendOperation? _cachedBufferListSendOperation;
private void ReturnOperation(AcceptOperation operation)
{
#endif
public readonly SocketAsyncContext AssociatedContext;
- public AsyncOperation Next;
- protected object CallbackOrEvent;
+ public AsyncOperation Next = null!; // initialized by helper called from ctor
+ protected object? CallbackOrEvent;
public SocketError ErrorCode;
- public byte[] SocketAddress;
+ public byte[]? SocketAddress;
public int SocketAddressLen;
public CancellationTokenRegistration CancellationRegistration;
- public ManualResetEventSlim Event
+ public ManualResetEventSlim? Event
{
get { return CallbackOrEvent as ManualResetEventSlim; }
set { CallbackOrEvent = value; }
// we can't pool the object, as ProcessQueue may still have a reference to it, due to
// using a pattern whereby it takes the lock to grab an item, but then releases the lock
// to do further processing on the item that's still in the list.
- ThreadPool.UnsafeQueueUserWorkItem(o => ((AsyncOperation)o).InvokeCallback(allowPooling: false), this);
+ ThreadPool.UnsafeQueueUserWorkItem(o => ((AsyncOperation)o!).InvokeCallback(allowPooling: false), this);
}
Trace("Exit");
public void Dispatch()
{
- ManualResetEventSlim e = Event;
+ ManualResetEventSlim? e = Event;
if (e != null)
{
// Sync operation. Signal waiting thread to continue processing.
public abstract void InvokeCallback(bool allowPooling);
[Conditional("SOCKETASYNCCONTEXT_TRACE")]
- public void Trace(string message, [CallerMemberName] string memberName = null)
+ public void Trace(string message, [CallerMemberName] string? memberName = null)
{
OutputTrace($"{IdOf(this)}.{memberName}: {message}");
}
[Conditional("SOCKETASYNCCONTEXT_TRACE")]
- public void TraceWithContext(SocketAsyncContext context, string message, [CallerMemberName] string memberName = null)
+ public void TraceWithContext(SocketAsyncContext context, string message, [CallerMemberName] string? memberName = null)
{
OutputTrace($"{IdOf(context)}, {IdOf(this)}.{memberName}: {message}");
}
protected sealed override void Abort() { }
- public Action<int, byte[], int, SocketFlags, SocketError> Callback
+ public Action<int, byte[]?, int, SocketFlags, SocketError>? Callback
{
set => CallbackOrEvent = value;
}
public override void InvokeCallback(bool allowPooling) =>
- ((Action<int, byte[], int, SocketFlags, SocketError>)CallbackOrEvent)(BytesTransferred, SocketAddress, SocketAddressLen, SocketFlags.None, ErrorCode);
+ ((Action<int, byte[]?, int, SocketFlags, SocketError>)CallbackOrEvent!)(BytesTransferred, SocketAddress, SocketAddressLen, SocketFlags.None, ErrorCode);
}
private sealed class BufferMemorySendOperation : SendOperation
public override void InvokeCallback(bool allowPooling)
{
- var cb = (Action<int, byte[], int, SocketFlags, SocketError>)CallbackOrEvent;
+ var cb = (Action<int, byte[]?, int, SocketFlags, SocketError>)CallbackOrEvent!;
int bt = BytesTransferred;
- byte[] sa = SocketAddress;
+ byte[]? sa = SocketAddress;
int sal = SocketAddressLen;
SocketError ec = ErrorCode;
private sealed class BufferListSendOperation : SendOperation
{
- public IList<ArraySegment<byte>> Buffers;
+ public IList<ArraySegment<byte>>? Buffers;
public int BufferIndex;
public BufferListSendOperation(SocketAsyncContext context) : base(context) { }
public override void InvokeCallback(bool allowPooling)
{
- var cb = (Action<int, byte[], int, SocketFlags, SocketError>)CallbackOrEvent;
+ var cb = (Action<int, byte[]?, int, SocketFlags, SocketError>)CallbackOrEvent!;
int bt = BytesTransferred;
- byte[] sa = SocketAddress;
+ byte[]? sa = SocketAddress;
int sal = SocketAddressLen;
SocketError ec = ErrorCode;
protected sealed override void Abort() { }
- public Action<int, byte[], int, SocketFlags, SocketError> Callback
+ public Action<int, byte[]?, int, SocketFlags, SocketError>? Callback
{
set => CallbackOrEvent = value;
}
public override void InvokeCallback(bool allowPooling) =>
- ((Action<int, byte[], int, SocketFlags, SocketError>)CallbackOrEvent)(
+ ((Action<int, byte[]?, int, SocketFlags, SocketError>)CallbackOrEvent!)(
BytesTransferred, SocketAddress, SocketAddressLen, ReceivedFlags, ErrorCode);
}
public override void InvokeCallback(bool allowPooling)
{
- var cb = (Action<int, byte[], int, SocketFlags, SocketError>)CallbackOrEvent;
+ var cb = (Action<int, byte[]?, int, SocketFlags, SocketError>)CallbackOrEvent!;
int bt = BytesTransferred;
- byte[] sa = SocketAddress;
+ byte[]? sa = SocketAddress;
int sal = SocketAddressLen;
SocketFlags rf = ReceivedFlags;
SocketError ec = ErrorCode;
private sealed class BufferListReceiveOperation : ReceiveOperation
{
- public IList<ArraySegment<byte>> Buffers;
+ public IList<ArraySegment<byte>>? Buffers;
public BufferListReceiveOperation(SocketAsyncContext context) : base(context) { }
public override void InvokeCallback(bool allowPooling)
{
- var cb = (Action<int, byte[], int, SocketFlags, SocketError>)CallbackOrEvent;
+ var cb = (Action<int, byte[]?, int, SocketFlags, SocketError>)CallbackOrEvent!;
int bt = BytesTransferred;
- byte[] sa = SocketAddress;
+ byte[]? sa = SocketAddress;
int sal = SocketAddressLen;
SocketFlags rf = ReceivedFlags;
SocketError ec = ErrorCode;
public SocketFlags Flags;
public int BytesTransferred;
public SocketFlags ReceivedFlags;
- public IList<ArraySegment<byte>> Buffers;
+ public IList<ArraySegment<byte>>? Buffers;
public bool IsIPv4;
public bool IsIPv6;
}
protected override bool DoTryComplete(SocketAsyncContext context) =>
- SocketPal.TryCompleteReceiveMessageFrom(context._socket, Buffer.Span, Buffers, Flags, SocketAddress, ref SocketAddressLen, IsIPv4, IsIPv6, out BytesTransferred, out ReceivedFlags, out IPPacketInformation, out ErrorCode);
+ SocketPal.TryCompleteReceiveMessageFrom(context._socket, Buffer.Span, Buffers, Flags, SocketAddress!, ref SocketAddressLen, IsIPv4, IsIPv6, out BytesTransferred, out ReceivedFlags, out IPPacketInformation, out ErrorCode);
public override void InvokeCallback(bool allowPooling) =>
- ((Action<int, byte[], int, SocketFlags, IPPacketInformation, SocketError>)CallbackOrEvent)(
- BytesTransferred, SocketAddress, SocketAddressLen, ReceivedFlags, IPPacketInformation, ErrorCode);
+ ((Action<int, byte[], int, SocketFlags, IPPacketInformation, SocketError>)CallbackOrEvent!)(
+ BytesTransferred, SocketAddress!, SocketAddressLen, ReceivedFlags, IPPacketInformation, ErrorCode);
}
private sealed class AcceptOperation : ReadOperation
public AcceptOperation(SocketAsyncContext context) : base(context) { }
- public Action<IntPtr, byte[], int, SocketError> Callback
+ public Action<IntPtr, byte[], int, SocketError>? Callback
{
set => CallbackOrEvent = value;
}
protected override bool DoTryComplete(SocketAsyncContext context)
{
- bool completed = SocketPal.TryCompleteAccept(context._socket, SocketAddress, ref SocketAddressLen, out AcceptedFileDescriptor, out ErrorCode);
+ bool completed = SocketPal.TryCompleteAccept(context._socket, SocketAddress!, ref SocketAddressLen, out AcceptedFileDescriptor, out ErrorCode);
Debug.Assert(ErrorCode == SocketError.Success || AcceptedFileDescriptor == (IntPtr)(-1), $"Unexpected values: ErrorCode={ErrorCode}, AcceptedFileDescriptor={AcceptedFileDescriptor}");
return completed;
}
public override void InvokeCallback(bool allowPooling)
{
- var cb = (Action<IntPtr, byte[], int, SocketError>)CallbackOrEvent;
+ var cb = (Action<IntPtr, byte[], int, SocketError>)CallbackOrEvent!;
IntPtr fd = AcceptedFileDescriptor;
- byte[] sa = SocketAddress;
+ byte[] sa = SocketAddress!;
int sal = SocketAddressLen;
SocketError ec = ErrorCode;
}
public override void InvokeCallback(bool allowPooling) =>
- ((Action<SocketError>)CallbackOrEvent)(ErrorCode);
+ ((Action<SocketError>)CallbackOrEvent!)(ErrorCode);
}
private sealed class SendFileOperation : WriteOperation
{
- public SafeFileHandle FileHandle;
+ public SafeFileHandle FileHandle = null!; // always set when constructed
public long Offset;
public long Count;
public long BytesTransferred;
}
public override void InvokeCallback(bool allowPooling) =>
- ((Action<long, SocketError>)CallbackOrEvent)(BytesTransferred, ErrorCode);
+ ((Action<long, SocketError>)CallbackOrEvent!)(BytesTransferred, ErrorCode);
protected override bool DoTryComplete(SocketAsyncContext context) =>
SocketPal.TryCompleteSendFile(context._socket, FileHandle, ref Offset, ref Count, ref BytesTransferred, out ErrorCode);
// since the last time we checked the state of the queue.
// If this happens, we MUST retry the operation, otherwise we risk
// "losing" the notification and causing the operation to pend indefinitely.
- private AsyncOperation _tail; // Queue of pending IO operations to process when data becomes available.
+ private AsyncOperation? _tail; // Queue of pending IO operations to process when data becomes available.
// The _queueLock is used to ensure atomic access to the queue state above.
// The lock is only ever held briefly, to read and/or update queue state, and
// call TryCancel, so we do this after the op is fully enqueued.
if (cancellationToken.CanBeCanceled)
{
- operation.CancellationRegistration = cancellationToken.UnsafeRegister(s => ((TOperation)s).TryCancel(), operation);
+ operation.CancellationRegistration = cancellationToken.UnsafeRegister(s => ((TOperation)s!).TryCancel(), operation);
}
return true;
// Remove the op from the queue and see if there's more to process.
- AsyncOperation nextOp = null;
+ AsyncOperation? nextOp = null;
using (Lock())
{
if (_state == QueueState.Stopped)
// Remove operation from queue.
// Note it must be there since it can only be processed and removed by the caller.
- AsyncOperation nextOp = null;
+ AsyncOperation? nextOp = null;
using (Lock())
{
if (_state == QueueState.Stopped)
}
[Conditional("SOCKETASYNCCONTEXT_TRACE")]
- public void Trace(SocketAsyncContext context, string message, [CallerMemberName] string memberName = null)
+ public void Trace(SocketAsyncContext context, string message, [CallerMemberName] string? memberName = null)
{
string queueType =
typeof(TOperation) == typeof(ReadOperation) ? "recv" :
return ReceiveFrom(buffer, ref flags, null, ref socketAddressLen, timeout, out bytesReceived);
}
- public SocketError ReceiveAsync(Memory<byte> buffer, SocketFlags flags, out int bytesReceived, out SocketFlags receivedFlags, Action<int, byte[], int, SocketFlags, SocketError> callback, CancellationToken cancellationToken)
+ public SocketError ReceiveAsync(Memory<byte> buffer, SocketFlags flags, out int bytesReceived, out SocketFlags receivedFlags, Action<int, byte[]?, int, SocketFlags, SocketError> callback, CancellationToken cancellationToken)
{
int socketAddressLen = 0;
return ReceiveFromAsync(buffer, flags, null, ref socketAddressLen, out bytesReceived, out receivedFlags, callback, cancellationToken);
}
- public SocketError ReceiveFrom(Memory<byte> buffer, ref SocketFlags flags, byte[] socketAddress, ref int socketAddressLen, int timeout, out int bytesReceived)
+ public SocketError ReceiveFrom(Memory<byte> buffer, ref SocketFlags flags, byte[]? socketAddress, ref int socketAddressLen, int timeout, out int bytesReceived)
{
Debug.Assert(timeout == -1 || timeout > 0, $"Unexpected timeout: {timeout}");
return operation.ErrorCode;
}
- public unsafe SocketError ReceiveFrom(Span<byte> buffer, ref SocketFlags flags, byte[] socketAddress, ref int socketAddressLen, int timeout, out int bytesReceived)
+ public unsafe SocketError ReceiveFrom(Span<byte> buffer, ref SocketFlags flags, byte[]? socketAddress, ref int socketAddressLen, int timeout, out int bytesReceived)
{
SocketFlags receivedFlags;
SocketError errorCode;
}
}
- public SocketError ReceiveFromAsync(Memory<byte> buffer, SocketFlags flags, byte[] socketAddress, ref int socketAddressLen, out int bytesReceived, out SocketFlags receivedFlags, Action<int, byte[], int, SocketFlags, SocketError> callback, CancellationToken cancellationToken = default)
+ public SocketError ReceiveFromAsync(Memory<byte> buffer, SocketFlags flags, byte[]? socketAddress, ref int socketAddressLen, out int bytesReceived, out SocketFlags receivedFlags, Action<int, byte[]?, int, SocketFlags, SocketError> callback, CancellationToken cancellationToken = default)
{
SetNonBlocking();
return ReceiveFrom(buffers, ref flags, null, 0, timeout, out bytesReceived);
}
- public SocketError ReceiveAsync(IList<ArraySegment<byte>> buffers, SocketFlags flags, out int bytesReceived, out SocketFlags receivedFlags, Action<int, byte[], int, SocketFlags, SocketError> callback)
+ public SocketError ReceiveAsync(IList<ArraySegment<byte>> buffers, SocketFlags flags, out int bytesReceived, out SocketFlags receivedFlags, Action<int, byte[]?, int, SocketFlags, SocketError> callback)
{
int socketAddressLen = 0;
return ReceiveFromAsync(buffers, flags, null, ref socketAddressLen, out bytesReceived, out receivedFlags, callback);
}
- public SocketError ReceiveFrom(IList<ArraySegment<byte>> buffers, ref SocketFlags flags, byte[] socketAddress, int socketAddressLen, int timeout, out int bytesReceived)
+ public SocketError ReceiveFrom(IList<ArraySegment<byte>> buffers, ref SocketFlags flags, byte[]? socketAddress, int socketAddressLen, int timeout, out int bytesReceived)
{
Debug.Assert(timeout == -1 || timeout > 0, $"Unexpected timeout: {timeout}");
return operation.ErrorCode;
}
- public SocketError ReceiveFromAsync(IList<ArraySegment<byte>> buffers, SocketFlags flags, byte[] socketAddress, ref int socketAddressLen, out int bytesReceived, out SocketFlags receivedFlags, Action<int, byte[], int, SocketFlags, SocketError> callback)
+ public SocketError ReceiveFromAsync(IList<ArraySegment<byte>> buffers, SocketFlags flags, byte[]? socketAddress, ref int socketAddressLen, out int bytesReceived, out SocketFlags receivedFlags, Action<int, byte[]?, int, SocketFlags, SocketError> callback)
{
SetNonBlocking();
}
public SocketError ReceiveMessageFrom(
- Memory<byte> buffer, IList<ArraySegment<byte>> buffers, ref SocketFlags flags, byte[] socketAddress, ref int socketAddressLen, bool isIPv4, bool isIPv6, int timeout, out IPPacketInformation ipPacketInformation, out int bytesReceived)
+ Memory<byte> buffer, IList<ArraySegment<byte>>? buffers, ref SocketFlags flags, byte[] socketAddress, ref int socketAddressLen, bool isIPv4, bool isIPv6, int timeout, out IPPacketInformation ipPacketInformation, out int bytesReceived)
{
Debug.Assert(timeout == -1 || timeout > 0, $"Unexpected timeout: {timeout}");
return operation.ErrorCode;
}
- public SocketError ReceiveMessageFromAsync(Memory<byte> buffer, IList<ArraySegment<byte>> buffers, SocketFlags flags, byte[] socketAddress, ref int socketAddressLen, bool isIPv4, bool isIPv6, out int bytesReceived, out SocketFlags receivedFlags, out IPPacketInformation ipPacketInformation, Action<int, byte[], int, SocketFlags, IPPacketInformation, SocketError> callback)
+ public SocketError ReceiveMessageFromAsync(Memory<byte> buffer, IList<ArraySegment<byte>>? buffers, SocketFlags flags, byte[] socketAddress, ref int socketAddressLen, bool isIPv4, bool isIPv6, out int bytesReceived, out SocketFlags receivedFlags, out IPPacketInformation ipPacketInformation, Action<int, byte[], int, SocketFlags, IPPacketInformation, SocketError> callback)
{
SetNonBlocking();
return SendTo(buffer, offset, count, flags, null, 0, timeout, out bytesSent);
}
- public SocketError SendAsync(Memory<byte> buffer, int offset, int count, SocketFlags flags, out int bytesSent, Action<int, byte[], int, SocketFlags, SocketError> callback, CancellationToken cancellationToken)
+ public SocketError SendAsync(Memory<byte> buffer, int offset, int count, SocketFlags flags, out int bytesSent, Action<int, byte[]?, int, SocketFlags, SocketError> callback, CancellationToken cancellationToken)
{
int socketAddressLen = 0;
return SendToAsync(buffer, offset, count, flags, null, ref socketAddressLen, out bytesSent, callback, cancellationToken);
}
- public SocketError SendTo(byte[] buffer, int offset, int count, SocketFlags flags, byte[] socketAddress, int socketAddressLen, int timeout, out int bytesSent)
+ public SocketError SendTo(byte[] buffer, int offset, int count, SocketFlags flags, byte[]? socketAddress, int socketAddressLen, int timeout, out int bytesSent)
{
Debug.Assert(timeout == -1 || timeout > 0, $"Unexpected timeout: {timeout}");
return operation.ErrorCode;
}
- public unsafe SocketError SendTo(ReadOnlySpan<byte> buffer, SocketFlags flags, byte[] socketAddress, int socketAddressLen, int timeout, out int bytesSent)
+ public unsafe SocketError SendTo(ReadOnlySpan<byte> buffer, SocketFlags flags, byte[]? socketAddress, int socketAddressLen, int timeout, out int bytesSent)
{
Debug.Assert(timeout == -1 || timeout > 0, $"Unexpected timeout: {timeout}");
}
}
- public SocketError SendToAsync(Memory<byte> buffer, int offset, int count, SocketFlags flags, byte[] socketAddress, ref int socketAddressLen, out int bytesSent, Action<int, byte[], int, SocketFlags, SocketError> callback, CancellationToken cancellationToken = default)
+ public SocketError SendToAsync(Memory<byte> buffer, int offset, int count, SocketFlags flags, byte[]? socketAddress, ref int socketAddressLen, out int bytesSent, Action<int, byte[]?, int, SocketFlags, SocketError> callback, CancellationToken cancellationToken = default)
{
SetNonBlocking();
return SendTo(buffers, flags, null, 0, timeout, out bytesSent);
}
- public SocketError SendAsync(IList<ArraySegment<byte>> buffers, SocketFlags flags, out int bytesSent, Action<int, byte[], int, SocketFlags, SocketError> callback)
+ public SocketError SendAsync(IList<ArraySegment<byte>> buffers, SocketFlags flags, out int bytesSent, Action<int, byte[]?, int, SocketFlags, SocketError> callback)
{
int socketAddressLen = 0;
return SendToAsync(buffers, flags, null, ref socketAddressLen, out bytesSent, callback);
}
- public SocketError SendTo(IList<ArraySegment<byte>> buffers, SocketFlags flags, byte[] socketAddress, int socketAddressLen, int timeout, out int bytesSent)
+ public SocketError SendTo(IList<ArraySegment<byte>> buffers, SocketFlags flags, byte[]? socketAddress, int socketAddressLen, int timeout, out int bytesSent)
{
Debug.Assert(timeout == -1 || timeout > 0, $"Unexpected timeout: {timeout}");
return operation.ErrorCode;
}
- public SocketError SendToAsync(IList<ArraySegment<byte>> buffers, SocketFlags flags, byte[] socketAddress, ref int socketAddressLen, out int bytesSent, Action<int, byte[], int, SocketFlags, SocketError> callback)
+ public SocketError SendToAsync(IList<ArraySegment<byte>> buffers, SocketFlags flags, byte[]? socketAddress, ref int socketAddressLen, out int bytesSent, Action<int, byte[]?, int, SocketFlags, SocketError> callback)
{
SetNonBlocking();
// (2) #define SOCKETASYNCCONTEXT_TRACE
[Conditional("SOCKETASYNCCONTEXT_TRACE")]
- public void Trace(string message, [CallerMemberName] string memberName = null)
+ public void Trace(string message, [CallerMemberName] string? memberName = null)
{
OutputTrace($"{IdOf(this)}.{memberName}: {message}");
}
//
public readonly struct Token
{
- private readonly SocketAsyncEngine _engine;
+ private readonly SocketAsyncEngine? _engine;
private readonly IntPtr _handle;
public Token(SocketAsyncContext context)
{
if (WasAllocated)
{
- _engine.FreeHandle(_handle);
+ _engine!.FreeHandle(_handle);
}
}
public bool TryRegister(SafeSocketHandle socket, out Interop.Error error)
{
Debug.Assert(WasAllocated, "Expected WasAllocated to be true");
- return _engine.TryRegister(socket, _handle, out error);
+ return _engine!.TryRegister(socket, _handle, out error);
}
}
// The current engines. We replace an engine when it runs out of "handle" values.
// Must be accessed under s_lock.
//
- private static readonly SocketAsyncEngine[] s_currentEngines = new SocketAsyncEngine[s_engineCount];
+ private static readonly SocketAsyncEngine?[] s_currentEngines = new SocketAsyncEngine?[s_engineCount];
private static int s_allocateFromEngine = 0;
private readonly IntPtr _port;
//
// Allocates a new {SocketAsyncEngine, handle} pair.
//
- private static void AllocateToken(SocketAsyncContext context, out SocketAsyncEngine engine, out IntPtr handle)
+ private static void AllocateToken(SocketAsyncContext context, out SocketAsyncEngine? engine, out IntPtr handle)
{
lock (s_lock)
{
{
if (suppressFlow) ExecutionContext.SuppressFlow();
Task.Factory.StartNew(
- s => ((SocketAsyncEngine)s).EventLoop(),
+ s => ((SocketAsyncEngine)s!).EventLoop(),
this,
CancellationToken.None,
TaskCreationOptions.LongRunning,
else
{
Debug.Assert(handle.ToInt64() < MaxHandles.ToInt64(), $"Unexpected values: handle={handle}, MaxHandles={MaxHandles}");
- _handleToContextMap.TryGetValue(handle, out SocketAsyncContext context);
+ _handleToContextMap.TryGetValue(handle, out SocketAsyncContext? context);
if (context != null)
{
context.HandleEvents(_buffer[i].Events);
private IntPtr _acceptedFileDescriptor;
private int _socketAddressSize;
private SocketFlags _receivedFlags;
- private Action<int, byte[], int, SocketFlags, SocketError> _transferCompletionCallback;
+ private Action<int, byte[]?, int, SocketFlags, SocketError>? _transferCompletionCallback;
private void InitializeInternals()
{
_acceptAddressBufferCount = socketAddressSize;
}
- internal unsafe SocketError DoOperationAccept(Socket socket, SafeSocketHandle handle, SafeSocketHandle acceptHandle)
+ internal unsafe SocketError DoOperationAccept(Socket socket, SafeSocketHandle handle, SafeSocketHandle? acceptHandle)
{
if (!_buffer.Equals(default))
{
IntPtr acceptedFd;
int socketAddressLen = _acceptAddressBufferCount / 2;
- SocketError socketError = handle.AsyncContext.AcceptAsync(_acceptBuffer, ref socketAddressLen, out acceptedFd, AcceptCompletionCallback);
+ SocketError socketError = handle.AsyncContext.AcceptAsync(_acceptBuffer!, ref socketAddressLen, out acceptedFd, AcceptCompletionCallback);
if (socketError != SocketError.IOPending)
{
- CompleteAcceptOperation(acceptedFd, _acceptBuffer, socketAddressLen, socketError);
+ CompleteAcceptOperation(acceptedFd, _acceptBuffer!, socketAddressLen, socketError);
FinishOperationSync(socketError, 0, SocketFlags.None);
}
internal unsafe SocketError DoOperationConnect(Socket socket, SafeSocketHandle handle)
{
- SocketError socketError = handle.AsyncContext.ConnectAsync(_socketAddress.Buffer, _socketAddress.Size, ConnectCompletionCallback);
+ SocketError socketError = handle.AsyncContext.ConnectAsync(_socketAddress!.Buffer, _socketAddress.Size, ConnectCompletionCallback);
if (socketError != SocketError.IOPending)
{
FinishOperationSync(socketError, 0, SocketFlags.None);
return socketError;
}
- private Action<int, byte[], int, SocketFlags, SocketError> TransferCompletionCallback =>
+ private Action<int, byte[]?, int, SocketFlags, SocketError> TransferCompletionCallback =>
_transferCompletionCallback ?? (_transferCompletionCallback = TransferCompletionCallbackCore);
- private void TransferCompletionCallbackCore(int bytesTransferred, byte[] socketAddress, int socketAddressSize, SocketFlags receivedFlags, SocketError socketError)
+ private void TransferCompletionCallbackCore(int bytesTransferred, byte[]? socketAddress, int socketAddressSize, SocketFlags receivedFlags, SocketError socketError)
{
CompleteTransferOperation(bytesTransferred, socketAddress, socketAddressSize, receivedFlags, socketError);
CompletionCallback(bytesTransferred, receivedFlags, socketError);
}
- private void CompleteTransferOperation(int bytesTransferred, byte[] socketAddress, int socketAddressSize, SocketFlags receivedFlags, SocketError socketError)
+ private void CompleteTransferOperation(int bytesTransferred, byte[]? socketAddress, int socketAddressSize, SocketFlags receivedFlags, SocketError socketError)
{
- Debug.Assert(socketAddress == null || socketAddress == _socketAddress.Buffer, $"Unexpected socketAddress: {socketAddress}");
+ Debug.Assert(socketAddress == null || socketAddress == _socketAddress!.Buffer, $"Unexpected socketAddress: {socketAddress}");
_socketAddressSize = socketAddressSize;
_receivedFlags = receivedFlags;
}
}
else
{
- errorCode = handle.AsyncContext.ReceiveAsync(_bufferListInternal, _socketFlags, out bytesReceived, out flags, TransferCompletionCallback);
+ errorCode = handle.AsyncContext.ReceiveAsync(_bufferListInternal!, _socketFlags, out bytesReceived, out flags, TransferCompletionCallback);
}
if (errorCode != SocketError.IOPending)
SocketFlags flags;
SocketError errorCode;
int bytesReceived = 0;
- int socketAddressLen = _socketAddress.Size;
+ int socketAddressLen = _socketAddress!.Size;
if (_bufferList == null)
{
errorCode = handle.AsyncContext.ReceiveFromAsync(_buffer.Slice(_offset, _count), _socketFlags, _socketAddress.Buffer, ref socketAddressLen, out bytesReceived, out flags, TransferCompletionCallback);
}
else
{
- errorCode = handle.AsyncContext.ReceiveFromAsync(_bufferListInternal, _socketFlags, _socketAddress.Buffer, ref socketAddressLen, out bytesReceived, out flags, TransferCompletionCallback);
+ errorCode = handle.AsyncContext.ReceiveFromAsync(_bufferListInternal!, _socketFlags, _socketAddress.Buffer, ref socketAddressLen, out bytesReceived, out flags, TransferCompletionCallback);
}
if (errorCode != SocketError.IOPending)
_socketAddressSize = 0;
bool isIPv4, isIPv6;
- Socket.GetIPProtocolInformation(socket.AddressFamily, _socketAddress, out isIPv4, out isIPv6);
+ Socket.GetIPProtocolInformation(socket.AddressFamily, _socketAddress!, out isIPv4, out isIPv6);
- int socketAddressSize = _socketAddress.Size;
+ int socketAddressSize = _socketAddress!.Size;
int bytesReceived;
SocketFlags receivedFlags;
IPPacketInformation ipPacketInformation;
}
else
{
- errorCode = handle.AsyncContext.SendAsync(_bufferListInternal, _socketFlags, out bytesSent, TransferCompletionCallback);
+ errorCode = handle.AsyncContext.SendAsync(_bufferListInternal!, _socketFlags, out bytesSent, TransferCompletionCallback);
}
if (errorCode != SocketError.IOPending)
{
for (int i = 0; i < elements.Length; i++)
{
- string path = elements[i]?.FilePath;
+ string? path = elements[i]?.FilePath;
if (path != null)
{
files[i] = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 0x1000, useAsync: true);
// this check, but it's good enough for most situations.
if (exc is FileNotFoundException fnfe)
{
- string dirname = Path.GetDirectoryName(fnfe.FileName);
+ string? dirname = Path.GetDirectoryName(fnfe.FileName);
if (!string.IsNullOrEmpty(dirname) && !Directory.Exists(dirname))
{
throw new DirectoryNotFoundException(fnfe.Message);
_socketAddressSize = 0;
int bytesSent;
- int socketAddressLen = _socketAddress.Size;
+ int socketAddressLen = _socketAddress!.Size;
SocketError errorCode;
if (_bufferList == null)
{
}
else
{
- errorCode = handle.AsyncContext.SendToAsync(_bufferListInternal, _socketFlags, _socketAddress.Buffer, ref socketAddressLen, out bytesSent, TransferCompletionCallback);
+ errorCode = handle.AsyncContext.SendToAsync(_bufferListInternal!, _socketFlags, _socketAddress.Buffer, ref socketAddressLen, out bytesSent, TransferCompletionCallback);
}
if (errorCode != SocketError.IOPending)
private SocketError FinishOperationAccept(Internals.SocketAddress remoteSocketAddress)
{
- System.Buffer.BlockCopy(_acceptBuffer, 0, remoteSocketAddress.Buffer, 0, _acceptAddressBufferCount);
- _acceptSocket = _currentSocket.CreateAcceptSocket(
+ System.Buffer.BlockCopy(_acceptBuffer!, 0, remoteSocketAddress.Buffer, 0, _acceptAddressBufferCount);
+ _acceptSocket = _currentSocket!.CreateAcceptSocket(
SocketPal.CreateSocket(_acceptedFileDescriptor),
- _currentSocket._rightEndPoint.Create(remoteSocketAddress));
+ _currentSocket._rightEndPoint!.Create(remoteSocketAddress));
return SocketError.Success;
}
}
else
{
- if (_currentSocket.Disposed)
+ if (_currentSocket!.Disposed)
{
socketError = SocketError.OperationAborted;
}
// BufferList property variables.
// Note that these arrays are allocated and then grown as necessary, but never shrunk.
// Thus the actual in-use length is defined by _bufferListInternal.Count, not the length of these arrays.
- private WSABuffer[] _wsaBufferArray;
- private GCHandle[] _multipleBufferGCHandles;
+ private WSABuffer[]? _wsaBufferArray;
+ private GCHandle[]? _multipleBufferGCHandles;
// Internal buffers for WSARecvMsg
- private byte[] _wsaMessageBuffer;
+ private byte[]? _wsaMessageBuffer;
private GCHandle _wsaMessageBufferGCHandle;
- private byte[] _controlBuffer;
+ private byte[]? _controlBuffer;
private GCHandle _controlBufferGCHandle;
- private WSABuffer[] _wsaRecvMsgWSABufferArray;
+ private WSABuffer[]? _wsaRecvMsgWSABufferArray;
private GCHandle _wsaRecvMsgWSABufferArrayGCHandle;
// Internal SocketAddress buffer
private GCHandle _socketAddressGCHandle;
- private Internals.SocketAddress _pinnedSocketAddress;
+ private Internals.SocketAddress? _pinnedSocketAddress;
// SendPacketsElements property variables.
- private FileStream[] _sendPacketsFileStreams;
+ private FileStream[]? _sendPacketsFileStreams;
// Overlapped object related variables.
- private PreAllocatedOverlapped _preAllocatedOverlapped;
- private readonly StrongBox<SocketAsyncEventArgs> _strongThisRef = new StrongBox<SocketAsyncEventArgs>(); // state for _preAllocatedOverlapped; .Value set to this while operations in flight
+ private PreAllocatedOverlapped _preAllocatedOverlapped = null!; // initialized by helper called from ctor
+ private readonly StrongBox<SocketAsyncEventArgs?> _strongThisRef = new StrongBox<SocketAsyncEventArgs?>(); // state for _preAllocatedOverlapped; .Value set to this while operations in flight
// Cancellation support
private CancellationTokenRegistration _registrationToCancelPendingIO;
{
// Try to cancel the I/O. We ignore the return value (other than for logging), as cancellation
// is opportunistic and we don't want to fail the operation because we couldn't cancel it.
- var thisRef = (SocketAsyncEventArgs)s;
- SafeSocketHandle handle = thisRef._currentSocket.SafeHandle;
+ var thisRef = (SocketAsyncEventArgs)s!;
+ SafeSocketHandle handle = thisRef._currentSocket!.SafeHandle;
if (!handle.IsClosed)
{
try
if (success)
{
// Synchronous success.
- if (_currentSocket.SafeHandle.SkipCompletionPortOnSuccess)
+ if (_currentSocket!.SafeHandle.SkipCompletionPortOnSuccess)
{
// The socket handle is configured to skip completion on success,
// so we can set the results right now.
if (socketError == SocketError.Success)
{
// Synchronous success.
- if (_currentSocket.SafeHandle.SkipCompletionPortOnSuccess)
+ if (_currentSocket!.SafeHandle.SkipCompletionPortOnSuccess)
{
// The socket handle is configured to skip completion on success,
// so we can set the results right now.
bool success = socket.ConnectEx(
handle,
PtrSocketAddressBuffer,
- _socketAddress.Size,
+ _socketAddress!.Size,
(IntPtr)((byte*)_singleBufferHandle.Pointer + _offset),
_count,
out int bytesTransferred,
SocketError socketError = Interop.Winsock.WSARecv(
handle,
_wsaBufferArray,
- _bufferListInternal.Count,
+ _bufferListInternal!.Count,
out int bytesTransferred,
ref flags,
overlapped,
SocketFlags flags = _socketFlags;
SocketError socketError = Interop.Winsock.WSARecvFrom(
handle,
- _wsaBufferArray,
- _bufferListInternal.Count,
+ _wsaBufferArray!,
+ _bufferListInternal!.Count,
out int bytesTransferred,
ref flags,
PtrSocketAddressBuffer,
}
// Create and pin an appropriately sized control buffer if none already
- IPAddress ipAddress = (_socketAddress.Family == AddressFamily.InterNetworkV6 ? _socketAddress.GetIPAddress() : null);
- bool ipv4 = (_currentSocket.AddressFamily == AddressFamily.InterNetwork || (ipAddress != null && ipAddress.IsIPv4MappedToIPv6)); // DualMode
+ IPAddress? ipAddress = (_socketAddress!.Family == AddressFamily.InterNetworkV6 ? _socketAddress.GetIPAddress() : null);
+ bool ipv4 = (_currentSocket!.AddressFamily == AddressFamily.InterNetwork || (ipAddress != null && ipAddress.IsIPv4MappedToIPv6)); // DualMode
bool ipv6 = _currentSocket.AddressFamily == AddressFamily.InterNetworkV6;
if (ipv4 && (_controlBuffer == null || _controlBuffer.Length != sizeof(Interop.Winsock.ControlData)))
else
{
// Use the multi-buffer WSABuffer.
- wsaRecvMsgWSABufferArray = _wsaBufferArray;
- wsaRecvMsgWSABufferCount = (uint)_bufferListInternal.Count;
+ wsaRecvMsgWSABufferArray = _wsaBufferArray!;
+ wsaRecvMsgWSABufferCount = (uint)_bufferListInternal!.Count;
}
// Ensure the array is pinned.
SocketError socketError = Interop.Winsock.WSASend(
handle,
_wsaBufferArray,
- _bufferListInternal.Count,
+ _bufferListInternal!.Count,
out int bytesTransferred,
_socketFlags,
overlapped,
out int bytesTransferred,
_socketFlags,
PtrSocketAddressBuffer,
- _socketAddress.Size,
+ _socketAddress!.Size,
overlapped,
IntPtr.Zero);
{
SocketError socketError = Interop.Winsock.WSASendTo(
handle,
- _wsaBufferArray,
- _bufferListInternal.Count,
+ _wsaBufferArray!,
+ _bufferListInternal!.Count,
out int bytesTransferred,
_socketFlags,
PtrSocketAddressBuffer,
- _socketAddress.Size,
+ _socketAddress!.Size,
overlapped,
IntPtr.Zero);
for (int i = 0; i < bufferCount; i++)
{
ArraySegment<byte> localCopy = _bufferListInternal[i];
- _wsaBufferArray[i].Pointer = Marshal.UnsafeAddrOfPinnedArrayElement(localCopy.Array, localCopy.Offset);
+ _wsaBufferArray[i].Pointer = Marshal.UnsafeAddrOfPinnedArrayElement(localCopy.Array!, localCopy.Offset);
_wsaBufferArray[i].Length = localCopy.Count;
}
}
// Pin down the new one.
- _socketAddressGCHandle = GCHandle.Alloc(_socketAddress.Buffer, GCHandleType.Pinned);
+ _socketAddressGCHandle = GCHandle.Alloc(_socketAddress!.Buffer, GCHandleType.Pinned);
_socketAddress.CopyAddressSizeIntoBuffer();
_pinnedSocketAddress = _socketAddress;
}
}
}
- private IntPtr PtrSocketAddressBufferSize => PtrSocketAddressBuffer + _socketAddress.GetAddressSizeOffset();
+ private IntPtr PtrSocketAddressBufferSize => PtrSocketAddressBuffer + _socketAddress!.GetAddressSizeOffset();
// Cleans up any existing Overlapped object and related state variables.
private void FreeOverlapped()
if (_preAllocatedOverlapped != null)
{
_preAllocatedOverlapped.Dispose();
- _preAllocatedOverlapped = null;
+ _preAllocatedOverlapped = null!;
}
}
else if (spe.FilePath != null)
{
// This element is a file.
- sendPacketsDescriptor[descriptorIndex].fileHandle = _sendPacketsFileStreams[fileIndex].SafeFileHandle.DangerousGetHandle();
+ sendPacketsDescriptor[descriptorIndex].fileHandle = _sendPacketsFileStreams![fileIndex].SafeFileHandle.DangerousGetHandle();
sendPacketsDescriptor[descriptorIndex].fileOffset = spe.OffsetLong;
sendPacketsDescriptor[descriptorIndex].length = (uint)spe.Count;
sendPacketsDescriptor[descriptorIndex].flags =
if (_bufferList != null)
{
- for (int i = 0; i < _bufferListInternal.Count; i++)
+ for (int i = 0; i < _bufferListInternal!.Count; i++)
{
- WSABuffer wsaBuffer = _wsaBufferArray[i];
+ WSABuffer wsaBuffer = _wsaBufferArray![i];
NetEventSource.DumpBuffer(this, wsaBuffer.Pointer, Math.Min(wsaBuffer.Length, size));
if ((size -= wsaBuffer.Length) <= 0)
{
IntPtr remoteAddr;
bool refAdded = false;
- SafeHandle safeHandle = _currentSocket.SafeHandle;
+ SafeHandle safeHandle = _currentSocket!.SafeHandle;
try
{
safeHandle.DangerousAddRef(ref refAdded);
Marshal.Copy(remoteAddr, remoteSocketAddress.Buffer, 0, remoteSocketAddress.Size);
socketError = Interop.Winsock.setsockopt(
- _acceptSocket.SafeHandle,
+ _acceptSocket!.SafeHandle,
SocketOptionLevel.Socket,
SocketOptionName.UpdateAcceptContext,
ref handle,
{
// Update the socket context.
SocketError socketError = Interop.Winsock.setsockopt(
- _currentSocket.SafeHandle,
+ _currentSocket!.SafeHandle,
SocketOptionLevel.Socket,
SocketOptionName.UpdateConnectContext,
null,
private unsafe void FinishOperationReceiveMessageFrom()
{
- Interop.Winsock.WSAMsg* PtrMessage = (Interop.Winsock.WSAMsg*)Marshal.UnsafeAddrOfPinnedArrayElement(_wsaMessageBuffer, 0);
+ Interop.Winsock.WSAMsg* PtrMessage = (Interop.Winsock.WSAMsg*)Marshal.UnsafeAddrOfPinnedArrayElement(_wsaMessageBuffer!, 0);
- if (_controlBuffer.Length == sizeof(Interop.Winsock.ControlData))
+ if (_controlBuffer!.Length == sizeof(Interop.Winsock.ControlData))
{
// IPv4.
_receiveMessageFromPacketInfo = SocketPal.GetIPPacketInformation((Interop.Winsock.ControlData*)PtrMessage->controlBuffer.Pointer);
private static readonly unsafe IOCompletionCallback s_completionPortCallback = delegate (uint errorCode, uint numBytes, NativeOverlapped* nativeOverlapped)
{
- var saeaBox = (StrongBox<SocketAsyncEventArgs>)ThreadPoolBoundHandle.GetNativeOverlappedState(nativeOverlapped);
+ var saeaBox = (StrongBox<SocketAsyncEventArgs>)ThreadPoolBoundHandle.GetNativeOverlappedState(nativeOverlapped)!;
+ Debug.Assert(saeaBox.Value != null);
SocketAsyncEventArgs saea = saeaBox.Value;
- Debug.Assert(saea != null);
if ((SocketError)errorCode == SocketError.Success)
{
if (socketError != SocketError.OperationAborted)
{
- if (_currentSocket.Disposed)
+ if (_currentSocket!.Disposed)
{
socketError = SocketError.OperationAborted;
}
public partial class SocketAsyncEventArgs : EventArgs, IDisposable
{
// AcceptSocket property variables.
- private Socket _acceptSocket;
- private Socket _connectSocket;
+ private Socket? _acceptSocket;
+ private Socket? _connectSocket;
// Single buffer.
private Memory<byte> _buffer;
private bool _bufferIsExplicitArray;
// BufferList property variables.
- private IList<ArraySegment<byte>> _bufferList;
- private List<ArraySegment<byte>> _bufferListInternal;
+ private IList<ArraySegment<byte>>? _bufferList;
+ private List<ArraySegment<byte>>? _bufferListInternal;
// BytesTransferred property variables.
private int _bytesTransferred;
private IPPacketInformation _receiveMessageFromPacketInfo;
// RemoteEndPoint property variables.
- private EndPoint _remoteEndPoint;
+ private EndPoint? _remoteEndPoint;
// SendPacketsSendSize property variable.
private int _sendPacketsSendSize;
// SendPacketsElements property variables.
- private SendPacketsElement[] _sendPacketsElements;
+ private SendPacketsElement[]? _sendPacketsElements;
// SendPacketsFlags property variable.
private TransmitFileOptions _sendPacketsFlags;
// SocketError property variables.
private SocketError _socketError;
- private Exception _connectByNameError;
+ private Exception? _connectByNameError;
// SocketFlags property variables.
private SocketFlags _socketFlags;
// UserToken property variables.
- private object _userToken;
+ private object? _userToken;
// Internal buffer for AcceptEx when Buffer not supplied.
- private byte[] _acceptBuffer;
+ private byte[]? _acceptBuffer;
private int _acceptAddressBufferCount;
// Internal SocketAddress buffer.
- internal Internals.SocketAddress _socketAddress;
+ internal Internals.SocketAddress? _socketAddress;
// Misc state variables.
private readonly bool _flowExecutionContext;
- private ExecutionContext _context;
+ private ExecutionContext? _context;
private static readonly ContextCallback s_executionCallback = ExecutionCallback;
- private Socket _currentSocket;
+ private Socket? _currentSocket;
private bool _userSocket; // if false when performing Connect, _currentSocket should be disposed
private bool _disposeCalled;
private const int Disposed = 2;
private int _operating;
- private MultipleConnectAsync _multipleConnect;
+ private MultipleConnectAsync? _multipleConnect;
public SocketAsyncEventArgs() : this(unsafeSuppressExecutionContextFlow: false)
{
InitializeInternals();
}
- public Socket AcceptSocket
+ public Socket? AcceptSocket
{
get { return _acceptSocket; }
set { _acceptSocket = value; }
}
- public Socket ConnectSocket
+ public Socket? ConnectSocket
{
get { return _connectSocket; }
}
- public byte[] Buffer
+ public byte[]? Buffer
{
get
{
// NOTE: this property is mutually exclusive with Buffer.
// Setting this property with an existing non-null Buffer will throw.
- public IList<ArraySegment<byte>> BufferList
+ public IList<ArraySegment<byte>>? BufferList
{
get { return _bufferList; }
set
get { return _bytesTransferred; }
}
- public event EventHandler<SocketAsyncEventArgs> Completed;
+ public event EventHandler<SocketAsyncEventArgs>? Completed;
protected virtual void OnCompleted(SocketAsyncEventArgs e)
{
get { return _receiveMessageFromPacketInfo; }
}
- public EndPoint RemoteEndPoint
+ public EndPoint? RemoteEndPoint
{
get { return _remoteEndPoint; }
set { _remoteEndPoint = value; }
}
- public SendPacketsElement[] SendPacketsElements
+ public SendPacketsElement[]? SendPacketsElements
{
get { return _sendPacketsElements; }
set
set { _socketError = value; }
}
- public Exception ConnectByNameError
+ public Exception? ConnectByNameError
{
get { return _connectByNameError; }
}
set { _socketFlags = value; }
}
- public object UserToken
+ public object? UserToken
{
get { return _userToken; }
set { _userToken = value; }
}
}
- public void SetBuffer(byte[] buffer, int offset, int count)
+ public void SetBuffer(byte[]? buffer, int offset, int count)
{
StartConfiguring();
try
}
else
{
- SocketException socketException = exception as SocketException;
+ SocketException? socketException = exception as SocketException;
if (socketException != null)
{
_socketError = socketException.SocketErrorCode;
}
}
- private static void ExecutionCallback(object state)
+ private static void ExecutionCallback(object? state)
{
- var thisRef = (SocketAsyncEventArgs)state;
+ var thisRef = (SocketAsyncEventArgs)state!;
thisRef.OnCompleted(thisRef);
}
// Prepares for a native async socket call.
// This method performs the tasks common to all socket operations.
- internal void StartOperationCommon(Socket socket, SocketAsyncOperation operation)
+ internal void StartOperationCommon(Socket? socket, SocketAsyncOperation operation)
{
// Change status to "in-use".
int status = Interlocked.CompareExchange(ref _operating, InProgress, Free);
// AcceptEx needs a single buffer that's the size of two native sockaddr buffers with 16
// extra bytes each. It can also take additional buffer space in front of those special
// sockaddr structures that can be filled in with initial data coming in on a connection.
- _acceptAddressBufferCount = 2 * (Socket.GetAddressSize(_currentSocket._rightEndPoint) + 16);
+ _acceptAddressBufferCount = 2 * (Socket.GetAddressSize(_currentSocket!._rightEndPoint!) + 16);
// If our caller specified a buffer (willing to get received data with the Accept) then
// it needs to be large enough for the two special sockaddr buffers that AcceptEx requires.
}
}
- internal void StartOperationConnect(MultipleConnectAsync multipleConnect, bool userSocket)
+ internal void StartOperationConnect(MultipleConnectAsync? multipleConnect, bool userSocket)
{
_multipleConnect = multipleConnect;
_connectSocket = null;
// the attempt socket will be closed anyways, so not updating the state is OK.
// If we're doing a static ConnectAsync to an IPEndPoint, we need to dispose
// of the socket, as we manufactured it and the caller has no opportunity to do so.
- Socket currentSocket = _currentSocket;
+ Socket? currentSocket = _currentSocket;
if (currentSocket != null)
{
currentSocket.UpdateStatusAfterSocketError(socketError);
internal void FinishOperationAsyncFailure(SocketError socketError, int bytesTransferred, SocketFlags flags)
{
- ExecutionContext context = _context; // store context before it's cleared as part of finishing the operation
+ ExecutionContext? context = _context; // store context before it's cleared as part of finishing the operation
FinishOperationSyncFailure(socketError, bytesTransferred, flags);
internal void FinishConnectByNameAsyncFailure(Exception exception, int bytesTransferred, SocketFlags flags)
{
- ExecutionContext context = _context; // store context before it's cleared as part of finishing the operation
+ ExecutionContext? context = _context; // store context before it's cleared as part of finishing the operation
FinishConnectByNameSyncFailure(exception, bytesTransferred, flags);
}
}
- internal void FinishWrapperConnectSuccess(Socket connectSocket, int bytesTransferred, SocketFlags flags)
+ internal void FinishWrapperConnectSuccess(Socket? connectSocket, int bytesTransferred, SocketFlags flags)
{
SetResults(SocketError.Success, bytesTransferred, flags);
_currentSocket = connectSocket;
_connectSocket = connectSocket;
// Complete the operation and raise the event.
- ExecutionContext context = _context; // store context before it's cleared as part of completing the operation
+ ExecutionContext? context = _context; // store context before it's cleared as part of completing the operation
Complete();
if (context == null)
{
{
case SocketAsyncOperation.Accept:
// Get the endpoint.
- Internals.SocketAddress remoteSocketAddress = IPEndPointExtensions.Serialize(_currentSocket._rightEndPoint);
+ Internals.SocketAddress remoteSocketAddress = IPEndPointExtensions.Serialize(_currentSocket!._rightEndPoint!);
socketError = FinishOperationAccept(remoteSocketAddress);
if (socketError == SocketError.Success)
{
- _acceptSocket = _currentSocket.UpdateAcceptSocket(_acceptSocket, _currentSocket._rightEndPoint.Create(remoteSocketAddress));
+ _acceptSocket = _currentSocket.UpdateAcceptSocket(_acceptSocket!, _currentSocket._rightEndPoint!.Create(remoteSocketAddress));
if (NetEventSource.IsEnabled) NetEventSource.Accepted(_acceptSocket, _acceptSocket.RemoteEndPoint, _acceptSocket.LocalEndPoint);
}
socketError = FinishOperationConnect();
if (socketError == SocketError.Success)
{
- if (NetEventSource.IsEnabled) NetEventSource.Connected(_currentSocket, _currentSocket.LocalEndPoint, _currentSocket.RemoteEndPoint);
+ if (NetEventSource.IsEnabled) NetEventSource.Connected(_currentSocket!, _currentSocket!.LocalEndPoint, _currentSocket.RemoteEndPoint);
// Mark socket connected.
- _currentSocket.SetToConnected();
+ _currentSocket!.SetToConnected();
_connectSocket = _currentSocket;
}
else
{
SetResults(socketError, bytesTransferred, flags);
- _currentSocket.UpdateStatusAfterSocketError(socketError);
+ _currentSocket!.UpdateStatusAfterSocketError(socketError);
}
break;
case SocketAsyncOperation.Disconnect:
- _currentSocket.SetToDisconnected();
+ _currentSocket!.SetToDisconnected();
_currentSocket._remoteEndPoint = null;
break;
case SocketAsyncOperation.ReceiveFrom:
// Deal with incoming address.
- _socketAddress.InternalSize = GetSocketAddressSize();
- Internals.SocketAddress socketAddressOriginal = IPEndPointExtensions.Serialize(_remoteEndPoint);
+ _socketAddress!.InternalSize = GetSocketAddressSize();
+ Internals.SocketAddress socketAddressOriginal = IPEndPointExtensions.Serialize(_remoteEndPoint!);
if (!socketAddressOriginal.Equals(_socketAddress))
{
try
{
- _remoteEndPoint = _remoteEndPoint.Create(_socketAddress);
+ _remoteEndPoint = _remoteEndPoint!.Create(_socketAddress);
}
catch
{
case SocketAsyncOperation.ReceiveMessageFrom:
// Deal with incoming address.
- _socketAddress.InternalSize = GetSocketAddressSize();
- socketAddressOriginal = IPEndPointExtensions.Serialize(_remoteEndPoint);
+ _socketAddress!.InternalSize = GetSocketAddressSize();
+ socketAddressOriginal = IPEndPointExtensions.Serialize(_remoteEndPoint!);
if (!socketAddressOriginal.Equals(_socketAddress))
{
try
{
- _remoteEndPoint = _remoteEndPoint.Create(_socketAddress);
+ _remoteEndPoint = _remoteEndPoint!.Create(_socketAddress);
}
catch
{
internal void FinishOperationAsyncSuccess(int bytesTransferred, SocketFlags flags)
{
- ExecutionContext context = _context; // store context before it's cleared as part of finishing the operation
+ ExecutionContext? context = _context; // store context before it's cleared as part of finishing the operation
FinishOperationSyncSuccess(bytesTransferred, flags);
return errorCode;
}
- private static unsafe int Receive(SafeSocketHandle socket, SocketFlags flags, Span<byte> buffer, byte[] socketAddress, ref int socketAddressLen, out SocketFlags receivedFlags, out Interop.Error errno)
+ private static unsafe int Receive(SafeSocketHandle socket, SocketFlags flags, Span<byte> buffer, byte[]? socketAddress, ref int socketAddressLen, out SocketFlags receivedFlags, out Interop.Error errno)
{
Debug.Assert(socketAddress != null || socketAddressLen == 0, $"Unexpected values: socketAddress={socketAddress}, socketAddressLen={socketAddressLen}");
return checked((int)received);
}
- private static unsafe int Send(SafeSocketHandle socket, SocketFlags flags, ReadOnlySpan<byte> buffer, ref int offset, ref int count, byte[] socketAddress, int socketAddressLen, out Interop.Error errno)
+ private static unsafe int Send(SafeSocketHandle socket, SocketFlags flags, ReadOnlySpan<byte> buffer, ref int offset, ref int count, byte[]? socketAddress, int socketAddressLen, out Interop.Error errno)
{
int sent;
fixed (byte* sockAddr = socketAddress)
return sent;
}
- private static unsafe int Send(SafeSocketHandle socket, SocketFlags flags, IList<ArraySegment<byte>> buffers, ref int bufferIndex, ref int offset, byte[] socketAddress, int socketAddressLen, out Interop.Error errno)
+ private static unsafe int Send(SafeSocketHandle socket, SocketFlags flags, IList<ArraySegment<byte>> buffers, ref int bufferIndex, ref int offset, byte[]? socketAddress, int socketAddressLen, out Interop.Error errno)
{
// Pin buffers and set up iovecs.
int startIndex = bufferIndex, startOffset = offset;
return bytesSent;
}
- private static unsafe int Receive(SafeSocketHandle socket, SocketFlags flags, IList<ArraySegment<byte>> buffers, byte[] socketAddress, ref int socketAddressLen, out SocketFlags receivedFlags, out Interop.Error errno)
+ private static unsafe int Receive(SafeSocketHandle socket, SocketFlags flags, IList<ArraySegment<byte>> buffers, byte[]? socketAddress, ref int socketAddressLen, out SocketFlags receivedFlags, out Interop.Error errno)
{
int available = 0;
errno = Interop.Sys.GetBytesAvailable(socket, &available);
return true;
}
- public static bool TryCompleteReceiveFrom(SafeSocketHandle socket, Span<byte> buffer, SocketFlags flags, byte[] socketAddress, ref int socketAddressLen, out int bytesReceived, out SocketFlags receivedFlags, out SocketError errorCode) =>
+ public static bool TryCompleteReceiveFrom(SafeSocketHandle socket, Span<byte> buffer, SocketFlags flags, byte[]? socketAddress, ref int socketAddressLen, out int bytesReceived, out SocketFlags receivedFlags, out SocketError errorCode) =>
TryCompleteReceiveFrom(socket, buffer, null, flags, socketAddress, ref socketAddressLen, out bytesReceived, out receivedFlags, out errorCode);
- public static bool TryCompleteReceiveFrom(SafeSocketHandle socket, IList<ArraySegment<byte>> buffers, SocketFlags flags, byte[] socketAddress, ref int socketAddressLen, out int bytesReceived, out SocketFlags receivedFlags, out SocketError errorCode) =>
+ public static bool TryCompleteReceiveFrom(SafeSocketHandle socket, IList<ArraySegment<byte>> buffers, SocketFlags flags, byte[]? socketAddress, ref int socketAddressLen, out int bytesReceived, out SocketFlags receivedFlags, out SocketError errorCode) =>
TryCompleteReceiveFrom(socket, default(Span<byte>), buffers, flags, socketAddress, ref socketAddressLen, out bytesReceived, out receivedFlags, out errorCode);
- public static unsafe bool TryCompleteReceiveFrom(SafeSocketHandle socket, Span<byte> buffer, IList<ArraySegment<byte>> buffers, SocketFlags flags, byte[] socketAddress, ref int socketAddressLen, out int bytesReceived, out SocketFlags receivedFlags, out SocketError errorCode)
+ public static unsafe bool TryCompleteReceiveFrom(SafeSocketHandle socket, Span<byte> buffer, IList<ArraySegment<byte>>? buffers, SocketFlags flags, byte[]? socketAddress, ref int socketAddressLen, out int bytesReceived, out SocketFlags receivedFlags, out SocketError errorCode)
{
try
{
}
}
- public static unsafe bool TryCompleteReceiveMessageFrom(SafeSocketHandle socket, Span<byte> buffer, IList<ArraySegment<byte>> buffers, SocketFlags flags, byte[] socketAddress, ref int socketAddressLen, bool isIPv4, bool isIPv6, out int bytesReceived, out SocketFlags receivedFlags, out IPPacketInformation ipPacketInformation, out SocketError errorCode)
+ public static unsafe bool TryCompleteReceiveMessageFrom(SafeSocketHandle socket, Span<byte> buffer, IList<ArraySegment<byte>>? buffers, SocketFlags flags, byte[] socketAddress, ref int socketAddressLen, bool isIPv4, bool isIPv6, out int bytesReceived, out SocketFlags receivedFlags, out IPPacketInformation ipPacketInformation, out SocketError errorCode)
{
try
{
}
}
- public static bool TryCompleteSendTo(SafeSocketHandle socket, Span<byte> buffer, ref int offset, ref int count, SocketFlags flags, byte[] socketAddress, int socketAddressLen, ref int bytesSent, out SocketError errorCode)
+ public static bool TryCompleteSendTo(SafeSocketHandle socket, Span<byte> buffer, ref int offset, ref int count, SocketFlags flags, byte[]? socketAddress, int socketAddressLen, ref int bytesSent, out SocketError errorCode)
{
int bufferIndex = 0;
return TryCompleteSendTo(socket, buffer, null, ref bufferIndex, ref offset, ref count, flags, socketAddress, socketAddressLen, ref bytesSent, out errorCode);
}
- public static bool TryCompleteSendTo(SafeSocketHandle socket, ReadOnlySpan<byte> buffer, SocketFlags flags, byte[] socketAddress, int socketAddressLen, ref int bytesSent, out SocketError errorCode)
+ public static bool TryCompleteSendTo(SafeSocketHandle socket, ReadOnlySpan<byte> buffer, SocketFlags flags, byte[]? socketAddress, int socketAddressLen, ref int bytesSent, out SocketError errorCode)
{
int bufferIndex = 0, offset = 0, count = buffer.Length;
return TryCompleteSendTo(socket, buffer, null, ref bufferIndex, ref offset, ref count, flags, socketAddress, socketAddressLen, ref bytesSent, out errorCode);
}
- public static bool TryCompleteSendTo(SafeSocketHandle socket, IList<ArraySegment<byte>> buffers, ref int bufferIndex, ref int offset, SocketFlags flags, byte[] socketAddress, int socketAddressLen, ref int bytesSent, out SocketError errorCode)
+ public static bool TryCompleteSendTo(SafeSocketHandle socket, IList<ArraySegment<byte>> buffers, ref int bufferIndex, ref int offset, SocketFlags flags, byte[]? socketAddress, int socketAddressLen, ref int bytesSent, out SocketError errorCode)
{
int count = 0;
return TryCompleteSendTo(socket, default(ReadOnlySpan<byte>), buffers, ref bufferIndex, ref offset, ref count, flags, socketAddress, socketAddressLen, ref bytesSent, out errorCode);
}
- public static bool TryCompleteSendTo(SafeSocketHandle socket, ReadOnlySpan<byte> buffer, IList<ArraySegment<byte>> buffers, ref int bufferIndex, ref int offset, ref int count, SocketFlags flags, byte[] socketAddress, int socketAddressLen, ref int bytesSent, out SocketError errorCode)
+ public static bool TryCompleteSendTo(SafeSocketHandle socket, ReadOnlySpan<byte> buffer, IList<ArraySegment<byte>>? buffers, ref int bufferIndex, ref int offset, ref int count, SocketFlags flags, byte[]? socketAddress, int socketAddressLen, ref int bytesSent, out SocketError errorCode)
{
bool successfulSend = false;
long start = socket.IsUnderlyingBlocking && socket.SendTimeout > 0 ? Environment.TickCount64 : 0; // Get ticks only if timeout is set and socket is blocking.
return completed ? errorCode : SocketError.WouldBlock;
}
- public static SocketError WindowsIoctl(SafeSocketHandle handle, int ioControlCode, byte[] optionInValue, byte[] optionOutValue, out int optionLength)
+ public static SocketError WindowsIoctl(SafeSocketHandle handle, int ioControlCode, byte[]? optionInValue, byte[]? optionOutValue, out int optionLength)
{
// Three codes are called out in the Winsock IOCTLs documentation as "The following Unix IOCTL codes (commands) are supported." They are
// also the three codes available for use with ioctlsocket on Windows. Developers should be discouraged from using Socket.IOControl in
return GetSocketErrorForErrorCode(err);
}
- public static unsafe SocketError GetMulticastOption(SafeSocketHandle handle, SocketOptionName optionName, out MulticastOption optionValue)
+ public static unsafe SocketError GetMulticastOption(SafeSocketHandle handle, SocketOptionName optionName, out MulticastOption? optionValue)
{
Debug.Assert(optionName == SocketOptionName.AddMembership || optionName == SocketOptionName.DropMembership, $"Unexpected optionName={optionName}");
return SocketError.Success;
}
- public static unsafe SocketError GetIPv6MulticastOption(SafeSocketHandle handle, SocketOptionName optionName, out IPv6MulticastOption optionValue)
+ public static unsafe SocketError GetIPv6MulticastOption(SafeSocketHandle handle, SocketOptionName optionName, out IPv6MulticastOption? optionValue)
{
Debug.Assert(optionName == SocketOptionName.AddMembership || optionName == SocketOptionName.DropMembership, $"Unexpected optionName={optionName}");
return SocketError.Success;
}
- public static unsafe SocketError GetLingerOption(SafeSocketHandle handle, out LingerOption optionValue)
+ public static unsafe SocketError GetLingerOption(SafeSocketHandle handle, out LingerOption? optionValue)
{
Interop.Sys.LingerOption opt = default;
Interop.Error err = Interop.Sys.GetLingerOption(handle, &opt);
return SocketError.Success;
}
- public static unsafe SocketError Select(IList checkRead, IList checkWrite, IList checkError, int microseconds)
+ public static unsafe SocketError Select(IList? checkRead, IList? checkWrite, IList? checkError, int microseconds)
{
int checkReadInitialCount = checkRead != null ? checkRead.Count : 0;
int checkWriteInitialCount = checkWrite != null ? checkWrite.Count : 0;
}
private static unsafe SocketError SelectViaPoll(
- IList checkRead, int checkReadInitialCount,
- IList checkWrite, int checkWriteInitialCount,
- IList checkError, int checkErrorInitialCount,
+ IList? checkRead, int checkReadInitialCount,
+ IList? checkWrite, int checkWriteInitialCount,
+ IList? checkError, int checkErrorInitialCount,
Interop.Sys.PollEvent* events, int eventsLength,
int microseconds)
{
}
}
- private static unsafe void AddToPollArray(Interop.Sys.PollEvent* arr, int arrLength, IList socketList, ref int arrOffset, Interop.Sys.PollEvents events, ref int refsAdded)
+ private static unsafe void AddToPollArray(Interop.Sys.PollEvent* arr, int arrLength, IList? socketList, ref int arrOffset, Interop.Sys.PollEvents events, ref int refsAdded)
{
if (socketList == null)
return;
throw new ArgumentOutOfRangeException(nameof(socketList));
}
- Socket socket = socketList[i] as Socket;
+ Socket? socket = socketList[i] as Socket;
if (socket == null)
{
throw new ArgumentException(SR.Format(SR.net_sockets_select, socket?.GetType().FullName ?? "null", typeof(Socket).FullName), nameof(socketList));
}
}
- private static unsafe void FilterPollList(IList socketList, Interop.Sys.PollEvent* arr, int arrEndOffset, Interop.Sys.PollEvents desiredEvents, ref int refsAdded)
+ private static unsafe void FilterPollList(IList? socketList, Interop.Sys.PollEvent* arr, int arrEndOffset, Interop.Sys.PollEvents desiredEvents, ref int refsAdded)
{
if (socketList == null)
return;
if ((arr[arrEndOffset].TriggeredEvents & desiredEvents) == 0)
{
- Socket socket = (Socket)socketList[i];
+ Socket socket = (Socket)socketList[i]!;
socket.InternalSafeHandle.DangerousRelease();
refsAdded--;
socketList.RemoveAt(i);
}
else
{
- FileStream fs = files[i] ?? e.FileStream;
+ FileStream fs = files[i] ?? e.FileStream!;
if (e.Count > fs.Length - e.OffsetLong)
{
throw new ArgumentOutOfRangeException();
if ((options & (TransmitFileOptions.Disconnect | TransmitFileOptions.ReuseSocket)) != 0)
{
await Task.Factory.FromAsync(
- (reuse, c, s) => ((Socket)s).BeginDisconnect(reuse, c, s),
- iar => ((Socket)iar.AsyncState).EndDisconnect(iar),
+ (reuse, c, s) => ((Socket)s!).BeginDisconnect(reuse, c, s),
+ iar => ((Socket)iar.AsyncState!).EndDisconnect(iar),
(options & TransmitFileOptions.ReuseSocket) != 0,
socket).ConfigureAwait(false);
}
return socketError;
}
- public static SocketError AcceptAsync(Socket socket, SafeSocketHandle handle, SafeSocketHandle acceptHandle, int receiveSize, int socketAddressSize, AcceptOverlappedAsyncResult asyncResult)
+ public static SocketError AcceptAsync(Socket socket, SafeSocketHandle handle, SafeSocketHandle? acceptHandle, int receiveSize, int socketAddressSize, AcceptOverlappedAsyncResult asyncResult)
{
Debug.Assert(acceptHandle == null, $"Unexpected acceptHandle: {acceptHandle}");
Debug.Assert(receiveSize == 0, $"Unexpected receiveSize: {receiveSize}");
int count = buffers.Count;
bool useStack = count <= StackThreshold;
- WSABuffer[] leasedWSA = null;
- GCHandle[] leasedGC = null;
+ WSABuffer[]? leasedWSA = null;
+ GCHandle[]? leasedGC = null;
Span<WSABuffer> WSABuffers = stackalloc WSABuffer[0];
Span<GCHandle> objectsToPin = stackalloc GCHandle[0];
if (useStack)
RangeValidationHelpers.ValidateSegment(buffer);
objectsToPin[i] = GCHandle.Alloc(buffer.Array, GCHandleType.Pinned);
WSABuffers[i].Length = buffer.Count;
- WSABuffers[i].Pointer = Marshal.UnsafeAddrOfPinnedArrayElement(buffer.Array, buffer.Offset);
+ WSABuffers[i].Pointer = Marshal.UnsafeAddrOfPinnedArrayElement(buffer.Array!, buffer.Offset);
}
unsafe
}
if (!useStack)
{
- ArrayPool<WSABuffer>.Shared.Return(leasedWSA);
- ArrayPool<GCHandle>.Shared.Return(leasedGC);
+ ArrayPool<WSABuffer>.Shared.Return(leasedWSA!);
+ ArrayPool<GCHandle>.Shared.Return(leasedGC!);
}
}
}
return SocketError.Success;
}
- public static unsafe SocketError SendFile(SafeSocketHandle handle, SafeFileHandle fileHandle, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags)
+ public static unsafe SocketError SendFile(SafeSocketHandle handle, SafeFileHandle? fileHandle, byte[]? preBuffer, byte[]? postBuffer, TransmitFileOptions flags)
{
fixed (byte* prePinnedBuffer = preBuffer)
fixed (byte* postPinnedBuffer = postBuffer)
int count = buffers.Count;
bool useStack = count <= StackThreshold;
- WSABuffer[] leasedWSA = null;
- GCHandle[] leasedGC = null;
+ WSABuffer[]? leasedWSA = null;
+ GCHandle[]? leasedGC = null;
Span<WSABuffer> WSABuffers = stackalloc WSABuffer[0];
Span<GCHandle> objectsToPin = stackalloc GCHandle[0];
if (useStack)
RangeValidationHelpers.ValidateSegment(buffer);
objectsToPin[i] = GCHandle.Alloc(buffer.Array, GCHandleType.Pinned);
WSABuffers[i].Length = buffer.Count;
- WSABuffers[i].Pointer = Marshal.UnsafeAddrOfPinnedArrayElement(buffer.Array, buffer.Offset);
+ WSABuffers[i].Pointer = Marshal.UnsafeAddrOfPinnedArrayElement(buffer.Array!, buffer.Offset);
}
unsafe
}
if (!useStack)
{
- ArrayPool<WSABuffer>.Shared.Return(leasedWSA);
- ArrayPool<GCHandle>.Shared.Return(leasedGC);
+ ArrayPool<WSABuffer>.Shared.Return(leasedWSA!);
+ ArrayPool<GCHandle>.Shared.Return(leasedGC!);
}
}
}
return SocketError.Success;
}
- public static SocketError WindowsIoctl(SafeSocketHandle handle, int ioControlCode, byte[] optionInValue, byte[] optionOutValue, out int optionLength)
+ public static SocketError WindowsIoctl(SafeSocketHandle handle, int ioControlCode, byte[]? optionInValue, byte[]? optionOutValue, out int optionLength)
{
if (ioControlCode == Interop.Winsock.IoctlSocketConstants.FIONBIO)
{
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
- public static SocketError GetMulticastOption(SafeSocketHandle handle, SocketOptionName optionName, out MulticastOption optionValue)
+ public static SocketError GetMulticastOption(SafeSocketHandle handle, SocketOptionName optionName, out MulticastOption? optionValue)
{
Interop.Winsock.IPMulticastRequest ipmr = default;
int optlen = Interop.Winsock.IPMulticastRequest.Size;
return SocketError.Success;
}
- public static SocketError GetIPv6MulticastOption(SafeSocketHandle handle, SocketOptionName optionName, out IPv6MulticastOption optionValue)
+ public static SocketError GetIPv6MulticastOption(SafeSocketHandle handle, SocketOptionName optionName, out IPv6MulticastOption? optionValue)
{
Interop.Winsock.IPv6MulticastRequest ipmr = default;
return SocketError.Success;
}
- public static SocketError GetLingerOption(SafeSocketHandle handle, out LingerOption optionValue)
+ public static SocketError GetLingerOption(SafeSocketHandle handle, out LingerOption? optionValue)
{
Interop.Winsock.Linger lngopt = default;
int optlen = 4;
}
}
- public static unsafe SocketError Select(IList checkRead, IList checkWrite, IList checkError, int microseconds)
+ public static unsafe SocketError Select(IList? checkRead, IList? checkWrite, IList? checkError, int microseconds)
{
const int StackThreshold = 64; // arbitrary limit to avoid too much space on stack
- bool ShouldStackAlloc(IList list, ref IntPtr[] lease, out Span<IntPtr> span)
+ bool ShouldStackAlloc(IList? list, ref IntPtr[]? lease, out Span<IntPtr> span)
{
int count;
if (list == null || (count = list.Count) == 0)
return true;
}
- IntPtr[] leaseRead = null, leaseWrite = null, leaseError = null;
+ IntPtr[]? leaseRead = null, leaseWrite = null, leaseError = null;
int refsAdded = 0;
try
{
SocketError errorCode = Interop.Winsock.WSASend(
handle,
asyncResult._wsaBuffers,
- asyncResult._wsaBuffers.Length,
+ asyncResult._wsaBuffers!.Length,
out bytesTransferred,
socketFlags,
asyncResult.DangerousOverlappedPointer, // SafeHandle was just created in SetUnmanagedStructures
private static unsafe bool TransmitFileHelper(
SafeHandle socket,
- SafeHandle fileHandle,
+ SafeHandle? fileHandle,
NativeOverlapped* overlapped,
- byte[] preBuffer,
- byte[] postBuffer,
+ byte[]? preBuffer,
+ byte[]? postBuffer,
TransmitFileOptions flags)
{
bool needTransmitFileBuffers = false;
return success;
}
- public static unsafe SocketError SendFileAsync(SafeSocketHandle handle, FileStream fileStream, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags, TransmitFileAsyncResult asyncResult)
+ public static unsafe SocketError SendFileAsync(SafeSocketHandle handle, FileStream? fileStream, byte[]? preBuffer, byte[]? postBuffer, TransmitFileOptions flags, TransmitFileAsyncResult asyncResult)
{
asyncResult.SetUnmanagedStructures(fileStream, preBuffer, postBuffer, (flags & (TransmitFileOptions.Disconnect | TransmitFileOptions.ReuseSocket)) != 0);
try
out bytesTransferred,
socketFlags,
asyncResult.GetSocketAddressPtr(),
- asyncResult.SocketAddress.Size,
+ asyncResult.SocketAddress!.Size,
asyncResult.DangerousOverlappedPointer, // SafeHandle was just created in SetUnmanagedStructures
IntPtr.Zero);
SocketError errorCode = Interop.Winsock.WSARecv(
handle,
asyncResult._wsaBuffers,
- asyncResult._wsaBuffers.Length,
+ asyncResult._wsaBuffers!.Length,
out bytesTransferred,
ref socketFlags,
asyncResult.DangerousOverlappedPointer, // SafeHandle was just created in SetUnmanagedStructures
int bytesTransfered;
SocketError errorCode = (SocketError)socket.WSARecvMsg(
handle,
- Marshal.UnsafeAddrOfPinnedArrayElement(asyncResult._messageBuffer, 0),
+ Marshal.UnsafeAddrOfPinnedArrayElement(asyncResult._messageBuffer!, 0),
out bytesTransfered,
asyncResult.DangerousOverlappedPointer, // SafeHandle was just created in SetUnmanagedStructures
IntPtr.Zero);
bool success = socket.AcceptEx(
handle,
acceptHandle,
- Marshal.UnsafeAddrOfPinnedArrayElement(asyncResult.Buffer, 0),
+ Marshal.UnsafeAddrOfPinnedArrayElement(asyncResult.Buffer!, 0),
receiveSize,
addressBufferSize,
addressBufferSize,
public static class SocketTaskExtensions
{
public static Task<Socket> AcceptAsync(this Socket socket) =>
- socket.AcceptAsync((Socket)null);
- public static Task<Socket> AcceptAsync(this Socket socket, Socket acceptSocket) =>
+ socket.AcceptAsync((Socket?)null);
+ public static Task<Socket> AcceptAsync(this Socket socket, Socket? acceptSocket) =>
socket.AcceptAsync(acceptSocket);
public static Task ConnectAsync(this Socket socket, EndPoint remoteEP) =>
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
public class TcpClient : IDisposable
{
private AddressFamily _family;
- private Socket _clientSocket;
- private NetworkStream _dataStream;
+ private Socket _clientSocket = null!; // initialized by helper called from ctor
+ private NetworkStream? _dataStream;
private volatile int _disposed;
private bool _active;
// Used by the class to provide the underlying network socket.
public Socket Client
{
- get { return Disposed ? null : _clientSocket; }
+ get { return Disposed ? null! : _clientSocket; }
set
{
_clientSocket = value;
// DNS when trying to connect. Use of AddressList[0] is
// bad form.
IPAddress[] addresses = Dns.GetHostAddresses(hostname);
- ExceptionDispatchInfo lastex = null;
+ ExceptionDispatchInfo? lastex = null;
try
{
{
var socket = new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
// Use of Interlocked.Exchanged ensures _clientSocket is written before Disposed is read.
- Interlocked.Exchange(ref _clientSocket, socket);
+ Interlocked.Exchange(ref _clientSocket!, socket);
if (Disposed)
{
// Dispose the socket so it throws ObjectDisposedException when we Connect.
}
catch
{
- _clientSocket = null;
+ _clientSocket = null!;
throw;
}
}
public Task ConnectAsync(IPAddress address, int port) =>
Task.Factory.FromAsync(
- (targetAddess, targetPort, callback, state) => ((TcpClient)state).BeginConnect(targetAddess, targetPort, callback, state),
- asyncResult => ((TcpClient)asyncResult.AsyncState).EndConnect(asyncResult),
+ (targetAddess, targetPort, callback, state) => ((TcpClient)state!).BeginConnect(targetAddess, targetPort, callback, state),
+ asyncResult => ((TcpClient)asyncResult.AsyncState!).EndConnect(asyncResult),
address, port, state: this);
public Task ConnectAsync(string host, int port) =>
Task.Factory.FromAsync(
- (targetHost, targetPort, callback, state) => ((TcpClient)state).BeginConnect(targetHost, targetPort, callback, state),
- asyncResult => ((TcpClient)asyncResult.AsyncState).EndConnect(asyncResult),
+ (targetHost, targetPort, callback, state) => ((TcpClient)state!).BeginConnect(targetHost, targetPort, callback, state),
+ asyncResult => ((TcpClient)asyncResult.AsyncState!).EndConnect(asyncResult),
host, port, state: this);
public Task ConnectAsync(IPAddress[] addresses, int port) =>
Task.Factory.FromAsync(
- (targetAddresses, targetPort, callback, state) => ((TcpClient)state).BeginConnect(targetAddresses, targetPort, callback, state),
- asyncResult => ((TcpClient)asyncResult.AsyncState).EndConnect(asyncResult),
+ (targetAddresses, targetPort, callback, state) => ((TcpClient)state!).BeginConnect(targetAddresses, targetPort, callback, state),
+ asyncResult => ((TcpClient)asyncResult.AsyncState!).EndConnect(asyncResult),
addresses, port, state: this);
- public IAsyncResult BeginConnect(IPAddress address, int port, AsyncCallback requestCallback, object state)
+ public IAsyncResult BeginConnect(IPAddress address, int port, AsyncCallback? requestCallback, object? state)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, address);
return result;
}
- public IAsyncResult BeginConnect(string host, int port, AsyncCallback requestCallback, object state)
+ public IAsyncResult BeginConnect(string host, int port, AsyncCallback? requestCallback, object? state)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, (string)host);
return result;
}
- public IAsyncResult BeginConnect(IPAddress[] addresses, int port, AsyncCallback requestCallback, object state)
+ public IAsyncResult BeginConnect(IPAddress[] addresses, int port, AsyncCallback? requestCallback, object? state)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, addresses);
{
if (disposing)
{
- IDisposable dataStream = _dataStream;
+ IDisposable? dataStream = _dataStream;
if (dataStream != null)
{
dataStream.Dispose();
// Gets or sets the size of the receive buffer in bytes.
public int ReceiveBufferSize
{
- get { return (int)Client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer); }
+ get { return (int)Client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer)!; }
set { Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, value); }
}
// Gets or sets the size of the send buffer in bytes.
public int SendBufferSize
{
- get { return (int)Client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer); }
+ get { return (int)Client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer)!; }
set { Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer, value); }
}
// Gets or sets the receive time out value of the connection in milliseconds.
public int ReceiveTimeout
{
- get { return (int)Client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout); }
+ get { return (int)Client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout)!; }
set { Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, value); }
}
// Gets or sets the send time out value of the connection in milliseconds.
public int SendTimeout
{
- get { return (int)Client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout); }
+ get { return (int)Client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout)!; }
set { Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, value); }
}
// Gets or sets the value of the connection's linger option.
- public LingerOption LingerState
+ [DisallowNull]
+ public LingerOption? LingerState
{
get { return Client.LingerState; }
- set { Client.LingerState = value; }
+ set { Client.LingerState = value!; }
}
// Enables or disables delay when send or receive buffers are full.
public class TcpListener
{
private readonly IPEndPoint _serverSocketEP;
- private Socket _serverSocket;
+ private Socket? _serverSocket;
private bool _active;
private bool _exclusiveAddressUse;
private bool? _allowNatTraversal;
get
{
CreateNewSocketIfNeeded();
- return _serverSocket;
+ return _serverSocket!;
}
}
{
get
{
- return _active ? _serverSocket.LocalEndPoint : _serverSocketEP;
+ return _active ? _serverSocket!.LocalEndPoint! : _serverSocketEP;
}
}
CreateNewSocketIfNeeded();
- _serverSocket.Bind(_serverSocketEP);
+ _serverSocket!.Bind(_serverSocketEP);
try
{
_serverSocket.Listen(backlog);
throw new InvalidOperationException(SR.net_stopped);
}
- return _serverSocket.Poll(0, SelectMode.SelectRead);
+ return _serverSocket!.Poll(0, SelectMode.SelectRead);
}
// Accept the first pending connection
throw new InvalidOperationException(SR.net_stopped);
}
- Socket socket = _serverSocket.Accept();
+ Socket socket = _serverSocket!.Accept();
if (NetEventSource.IsEnabled) NetEventSource.Exit(this, socket);
return socket;
throw new InvalidOperationException(SR.net_stopped);
}
- Socket acceptedSocket = _serverSocket.Accept();
+ Socket acceptedSocket = _serverSocket!.Accept();
TcpClient returnValue = new TcpClient(acceptedSocket);
if (NetEventSource.IsEnabled) NetEventSource.Exit(this, returnValue);
return returnValue;
}
- public IAsyncResult BeginAcceptSocket(AsyncCallback callback, object state)
+ public IAsyncResult BeginAcceptSocket(AsyncCallback? callback, object? state)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
throw new InvalidOperationException(SR.net_stopped);
}
- IAsyncResult result = _serverSocket.BeginAccept(callback, state);
+ IAsyncResult result = _serverSocket!.BeginAccept(callback, state);
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
return result;
throw new ArgumentNullException(nameof(asyncResult));
}
- LazyAsyncResult lazyResult = asyncResult as LazyAsyncResult;
- Socket asyncSocket = lazyResult == null ? null : lazyResult.AsyncObject as Socket;
+ LazyAsyncResult? lazyResult = asyncResult as LazyAsyncResult;
+ Socket? asyncSocket = lazyResult == null ? null : lazyResult.AsyncObject as Socket;
if (asyncSocket == null)
{
throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
return socket;
}
- public IAsyncResult BeginAcceptTcpClient(AsyncCallback callback, object state)
+ public IAsyncResult BeginAcceptTcpClient(AsyncCallback? callback, object? state)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
throw new InvalidOperationException(SR.net_stopped);
}
- IAsyncResult result = _serverSocket.BeginAccept(callback, state);
+ IAsyncResult result = _serverSocket!.BeginAccept(callback, state);
if (NetEventSource.IsEnabled) NetEventSource.Exit(this, result);
return result;
}
throw new ArgumentNullException(nameof(asyncResult));
}
- LazyAsyncResult lazyResult = asyncResult as LazyAsyncResult;
- Socket asyncSocket = lazyResult == null ? null : lazyResult.AsyncObject as Socket;
+ LazyAsyncResult? lazyResult = asyncResult as LazyAsyncResult;
+ Socket? asyncSocket = lazyResult == null ? null : lazyResult.AsyncObject as Socket;
if (asyncSocket == null)
{
throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
public Task<Socket> AcceptSocketAsync()
{
return Task<Socket>.Factory.FromAsync(
- (callback, state) => ((TcpListener)state).BeginAcceptSocket(callback, state),
- asyncResult => ((TcpListener)asyncResult.AsyncState).EndAcceptSocket(asyncResult),
+ (callback, state) => ((TcpListener)state!).BeginAcceptSocket(callback, state),
+ asyncResult => ((TcpListener)asyncResult.AsyncState!).EndAcceptSocket(asyncResult),
state: this);
}
public Task<TcpClient> AcceptTcpClientAsync()
{
return Task<TcpClient>.Factory.FromAsync(
- (callback, state) => ((TcpListener)state).BeginAcceptTcpClient(callback, state),
- asyncResult => ((TcpListener)asyncResult.AsyncState).EndAcceptTcpClient(asyncResult),
+ (callback, state) => ((TcpListener)state!).BeginAcceptTcpClient(callback, state),
+ asyncResult => ((TcpListener)asyncResult.AsyncState!).EndAcceptTcpClient(asyncResult),
state: this);
}
}
private void SetIPProtectionLevel(bool allowed)
- => _serverSocket.SetIPProtectionLevel(allowed ? IPProtectionLevel.Unrestricted : IPProtectionLevel.EdgeRestricted);
+ => _serverSocket!.SetIPProtectionLevel(allowed ? IPProtectionLevel.Unrestricted : IPProtectionLevel.EdgeRestricted);
private void CreateNewSocketIfNeeded()
{
{
internal sealed class TransmitFileAsyncResult : BaseOverlappedAsyncResult
{
- private FileStream _fileStream;
+ private FileStream? _fileStream;
private bool _doDisconnect;
- internal TransmitFileAsyncResult(Socket socket, object asyncState, AsyncCallback asyncCallback) :
+ internal TransmitFileAsyncResult(Socket socket, object? asyncState, AsyncCallback? asyncCallback) :
base(socket, asyncState, asyncCallback)
{
}
- internal void SetUnmanagedStructures(FileStream fileStream, byte[] preBuffer, byte[] postBuffer, bool doDisconnect)
+ internal void SetUnmanagedStructures(FileStream? fileStream, byte[]? preBuffer, byte[]? postBuffer, bool doDisconnect)
{
_fileStream = fileStream;
_doDisconnect = doDisconnect;
if (postBuffer != null && postBuffer.Length > 0)
++buffsNumber;
- object[] objectsToPin = null;
+ object[]? objectsToPin = null;
if (buffsNumber != 0)
{
objectsToPin = new object[buffsNumber];
// 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.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
namespace System.Net.Sockets
{
private const int MaxUDPSize = 0x10000;
- private Socket _clientSocket;
+ private Socket _clientSocket = null!; // initialized by helper called from ctor
private bool _active;
private readonly byte[] _buffer = new byte[MaxUDPSize];
private AddressFamily _family = AddressFamily.InterNetwork;
// of the Bind() call and free the bound IPEndPoint.
chkClientSocket.InternalShutdown(SocketShutdown.Both);
chkClientSocket.Dispose();
- _clientSocket = null;
+ _clientSocket = null!;
}
_disposed = true;
}
}
- public IAsyncResult BeginSend(byte[] datagram, int bytes, IPEndPoint endPoint, AsyncCallback requestCallback, object state)
+ public IAsyncResult BeginSend(byte[] datagram, int bytes, IPEndPoint? endPoint, AsyncCallback? requestCallback, object? state)
{
ThrowIfDisposed();
return _clientSocket.BeginSendTo(datagram, 0, bytes, SocketFlags.None, endPoint, requestCallback, state);
}
- public IAsyncResult BeginSend(byte[] datagram, int bytes, string hostname, int port, AsyncCallback requestCallback, object state)
+ public IAsyncResult BeginSend(byte[] datagram, int bytes, string? hostname, int port, AsyncCallback? requestCallback, object? state)
{
if (_active && ((hostname != null) || (port != 0)))
{
throw new InvalidOperationException(SR.net_udpconnected);
}
- IPEndPoint ipEndPoint = null;
+ IPEndPoint? ipEndPoint = null;
if (hostname != null && port != 0)
{
IPAddress[] addresses = Dns.GetHostAddresses(hostname);
return BeginSend(datagram, bytes, ipEndPoint, requestCallback, state);
}
- public IAsyncResult BeginSend(byte[] datagram, int bytes, AsyncCallback requestCallback, object state)
+ public IAsyncResult BeginSend(byte[] datagram, int bytes, AsyncCallback? requestCallback, object? state)
{
return BeginSend(datagram, bytes, null, requestCallback, state);
}
}
}
- public IAsyncResult BeginReceive(AsyncCallback requestCallback, object state)
+ public IAsyncResult BeginReceive(AsyncCallback? requestCallback, object? state)
{
// Validate input parameters.
ThrowIfDisposed();
return _clientSocket.BeginReceiveFrom(_buffer, 0, MaxUDPSize, SocketFlags.None, ref tempRemoteEP, requestCallback, state);
}
- public byte[] EndReceive(IAsyncResult asyncResult, ref IPEndPoint remoteEP)
+ public byte[] EndReceive(IAsyncResult asyncResult, ref IPEndPoint? remoteEP)
{
ThrowIfDisposed();
public Task<int> SendAsync(byte[] datagram, int bytes)
{
return Task<int>.Factory.FromAsync(
- (targetDatagram, targetBytes, callback, state) => ((UdpClient)state).BeginSend(targetDatagram, targetBytes, callback, state),
- asyncResult => ((UdpClient)asyncResult.AsyncState).EndSend(asyncResult),
+ (targetDatagram, targetBytes, callback, state) => ((UdpClient)state!).BeginSend(targetDatagram, targetBytes, callback, state),
+ asyncResult => ((UdpClient)asyncResult.AsyncState!).EndSend(asyncResult),
datagram,
bytes,
state: this);
}
- public Task<int> SendAsync(byte[] datagram, int bytes, IPEndPoint endPoint)
+ public Task<int> SendAsync(byte[] datagram, int bytes, IPEndPoint? endPoint)
{
return Task<int>.Factory.FromAsync(
- (targetDatagram, targetBytes, targetEndpoint, callback, state) => ((UdpClient)state).BeginSend(targetDatagram, targetBytes, targetEndpoint, callback, state),
- asyncResult => ((UdpClient)asyncResult.AsyncState).EndSend(asyncResult),
+ (targetDatagram, targetBytes, targetEndpoint, callback, state) => ((UdpClient)state!).BeginSend(targetDatagram, targetBytes, targetEndpoint, callback, state),
+ asyncResult => ((UdpClient)asyncResult.AsyncState!).EndSend(asyncResult),
datagram,
bytes,
endPoint,
state: this);
}
- public Task<int> SendAsync(byte[] datagram, int bytes, string hostname, int port)
+ public Task<int> SendAsync(byte[] datagram, int bytes, string? hostname, int port)
{
- Tuple<byte[], string> packedArguments = Tuple.Create(datagram, hostname);
+ Tuple<byte[], string?> packedArguments = Tuple.Create(datagram, hostname);
return Task<int>.Factory.FromAsync(
(targetPackedArguments, targetBytes, targetPort, callback, state) =>
{
byte[] targetDatagram = targetPackedArguments.Item1;
- string targetHostname = targetPackedArguments.Item2;
- var client = (UdpClient)state;
+ string? targetHostname = targetPackedArguments.Item2;
+ var client = (UdpClient)state!;
return client.BeginSend(targetDatagram, targetBytes, targetHostname, targetPort, callback, state);
},
- asyncResult => ((UdpClient)asyncResult.AsyncState).EndSend(asyncResult),
+ asyncResult => ((UdpClient)asyncResult.AsyncState!).EndSend(asyncResult),
packedArguments,
bytes,
port,
public Task<UdpReceiveResult> ReceiveAsync()
{
return Task<UdpReceiveResult>.Factory.FromAsync(
- (callback, state) => ((UdpClient)state).BeginReceive(callback, state),
+ (callback, state) => ((UdpClient)state!).BeginReceive(callback, state),
asyncResult =>
{
- var client = (UdpClient)asyncResult.AsyncState;
- IPEndPoint remoteEP = null;
+ var client = (UdpClient)asyncResult.AsyncState!;
+ IPEndPoint? remoteEP = null;
byte[] buffer = client.EndReceive(asyncResult, ref remoteEP);
- return new UdpReceiveResult(buffer, remoteEP);
+ return new UdpReceiveResult(buffer, remoteEP!);
},
state: this);
}
IPAddress[] addresses = Dns.GetHostAddresses(hostname);
- Exception lastex = null;
- Socket ipv6Socket = null;
- Socket ipv4Socket = null;
+ Exception? lastex = null;
+ Socket? ipv6Socket = null;
+ Socket? ipv4Socket = null;
try
{
_active = true;
}
- public byte[] Receive(ref IPEndPoint remoteEP)
+ public byte[] Receive([NotNull] ref IPEndPoint? remoteEP)
{
ThrowIfDisposed();
// Sends a UDP datagram to the host at the remote end point.
- public int Send(byte[] dgram, int bytes, IPEndPoint endPoint)
+ public int Send(byte[] dgram, int bytes, IPEndPoint? endPoint)
{
ThrowIfDisposed();
// Sends a UDP datagram to the specified port on the specified remote host.
- public int Send(byte[] dgram, int bytes, string hostname, int port)
+ public int Send(byte[] dgram, int bytes, string? hostname, int port)
{
ThrowIfDisposed();
/// </summary>
/// <param name="obj">The object to compare with this instance</param>
/// <returns>true if obj is an instance of <see cref="UdpReceiveResult"/> and equals the value of the instance; otherwise, false</returns>
- public override bool Equals(object obj) =>
+ public override bool Equals(object? obj) =>
obj is UdpReceiveResult other && Equals(other);
/// <summary>
using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
AssertExtensions.Throws<ArgumentNullException>("asyncResult", () => s.EndDisconnect(null));
+ AssertExtensions.Throws<ArgumentNullException>("e", () => s.DisconnectAsync(null));
AssertExtensions.Throws<ArgumentException>("asyncResult", () => s.EndDisconnect(Task.CompletedTask));
s.Dispose();
Assert.Throws<ObjectDisposedException>(() => s.Disconnect(true));