Welcome to mirror list, hosted at ThFree Co, Russian Federation.

SocketAsyncEventArgs.cs « Sockets « Net « System « src « System.Net.Sockets « src - github.com/mono/corefx.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 1c7f2d81c00dc4100f999d238d200ae96050c948 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Threading;

namespace System.Net.Sockets
{
    public partial class SocketAsyncEventArgs : EventArgs, IDisposable
    {
        // AcceptSocket property variables.
        internal Socket _acceptSocket;
        private Socket _connectSocket;

        // Buffer,Offset,Count property variables.
        internal byte[] _buffer;
        internal int _count;
        internal int _offset;

        // BufferList property variables.
        internal IList<ArraySegment<byte>> _bufferList;

        // BytesTransferred property variables.
        private int _bytesTransferred;

        // Completed event property variables.
        private event EventHandler<SocketAsyncEventArgs> _completed;
        private bool _completedChanged;

        // DisconnectReuseSocket propery variables.
        private bool _disconnectReuseSocket;

        // LastOperation property variables.
        private SocketAsyncOperation _completedOperation;

        // ReceiveMessageFromPacketInfo property variables.
        private IPPacketInformation _receiveMessageFromPacketInfo;

        // RemoteEndPoint property variables.
        private EndPoint _remoteEndPoint;

        // SendPacketsSendSize property variable.
        internal int _sendPacketsSendSize;

        // SendPacketsElements property variables.
        internal SendPacketsElement[] _sendPacketsElements;

        // SocketError property variables.
        private SocketError _socketError;
        private Exception _connectByNameError;

        // SocketFlags property variables.
        internal SocketFlags _socketFlags;

        // UserToken property variables.
        private object _userToken;

        // Internal buffer for AcceptEx when Buffer not supplied.
        internal byte[] _acceptBuffer;
        internal int _acceptAddressBufferCount;

        // Internal SocketAddress buffer.
        internal Internals.SocketAddress _socketAddress;

        // Misc state variables.
        private ExecutionContext _context;
        private static readonly ContextCallback s_executionCallback = ExecutionCallback;
        private Socket _currentSocket;
        private bool _disposeCalled;

        // Controls thread safety via Interlocked.
        private const int Configuring = -1;
        private const int Free = 0;
        private const int InProgress = 1;
        private const int Disposed = 2;
        private int _operating;

        private MultipleConnectAsync _multipleConnect;

        private static bool s_loggingEnabled = SocketsEventSource.Log.IsEnabled();

        public SocketAsyncEventArgs()
        {
            InitializeInternals();
        }

        public Socket AcceptSocket
        {
            get { return _acceptSocket; }
            set { _acceptSocket = value; }
        }

        public Socket ConnectSocket
        {
            get { return _connectSocket; }
        }

        public byte[] Buffer
        {
            get { return _buffer; }
        }

        public int Offset
        {
            get { return _offset; }
        }

        public int Count
        {
            get { return _count; }
        }

        // NOTE: this property is mutually exclusive with Buffer.
        // Setting this property with an existing non-null Buffer will throw.    
        public IList<ArraySegment<byte>> BufferList
        {
            get { return _bufferList; }
            set
            {
                StartConfiguring();
                try
                {
                    if (value != null && _buffer != null)
                    {
                        throw new ArgumentException(SR.Format(SR.net_ambiguousbuffers, "Buffer"));
                    }
                    _bufferList = value;
                    SetupMultipleBuffers();
                }
                finally
                {
                    Complete();
                }
            }
        }

        public int BytesTransferred
        {
            get { return _bytesTransferred; }
        }

        public event EventHandler<SocketAsyncEventArgs> Completed
        {
            add
            {
                _completed += value;
                _completedChanged = true;
            }
            remove
            {
                _completed -= value;
                _completedChanged = true;
            }
        }

        protected virtual void OnCompleted(SocketAsyncEventArgs e)
        {
            EventHandler<SocketAsyncEventArgs> handler = _completed;
            if (handler != null)
            {
                handler(e._currentSocket, e);
            }
        }

        // DisconnectResuseSocket property.
        public bool DisconnectReuseSocket
        {
            get { return _disconnectReuseSocket; }
            set { _disconnectReuseSocket = value; }
        }

        public SocketAsyncOperation LastOperation
        {
            get { return _completedOperation; }
        }

        public IPPacketInformation ReceiveMessageFromPacketInfo
        {
            get { return _receiveMessageFromPacketInfo; }
        }

        public EndPoint RemoteEndPoint
        {
            get { return _remoteEndPoint; }
            set { _remoteEndPoint = value; }
        }

        public SendPacketsElement[] SendPacketsElements
        {
            get { return _sendPacketsElements; }
            set
            {
                StartConfiguring();
                try
                {
                    _sendPacketsElements = value;
                    SetupSendPacketsElements();
                }
                finally
                {
                    Complete();
                }
            }
        }

        public int SendPacketsSendSize
        {
            get { return _sendPacketsSendSize; }
            set { _sendPacketsSendSize = value; }
        }

        public SocketError SocketError
        {
            get { return _socketError; }
            set { _socketError = value; }
        }

        public Exception ConnectByNameError
        {
            get { return _connectByNameError; }
        }

        public SocketFlags SocketFlags
        {
            get { return _socketFlags; }
            set { _socketFlags = value; }
        }

        public object UserToken
        {
            get { return _userToken; }
            set { _userToken = value; }
        }

        public void SetBuffer(byte[] buffer, int offset, int count)
        {
            SetBufferInternal(buffer, offset, count);
        }

        public void SetBuffer(int offset, int count)
        {
            SetBufferInternal(_buffer, offset, count);
        }

        private void SetBufferInternal(byte[] buffer, int offset, int count)
        {
            StartConfiguring();
            try
            {
                if (buffer == null)
                {
                    // Clear out existing buffer.
                    _buffer = null;
                    _offset = 0;
                    _count = 0;
                }
                else
                {
                    // Can't have both Buffer and BufferList.
                    if (_bufferList != null)
                    {
                        throw new ArgumentException(SR.Format(SR.net_ambiguousbuffers, "BufferList"));
                    }

                    // Offset and count can't be negative and the 
                    // combination must be in bounds of the array.
                    if (offset < 0 || offset > buffer.Length)
                    {
                        throw new ArgumentOutOfRangeException(nameof(offset));
                    }
                    if (count < 0 || count > (buffer.Length - offset))
                    {
                        throw new ArgumentOutOfRangeException(nameof(count));
                    }

                    _buffer = buffer;
                    _offset = offset;
                    _count = count;
                }

                // Pin new or unpin old buffer if necessary.
                SetupSingleBuffer();
            }
            finally
            {
                Complete();
            }
        }

        internal void SetResults(SocketError socketError, int bytesTransferred, SocketFlags flags)
        {
            _socketError = socketError;
            _connectByNameError = null;
            _bytesTransferred = bytesTransferred;
            _socketFlags = flags;
        }

        internal void SetResults(Exception exception, int bytesTransferred, SocketFlags flags)
        {
            _connectByNameError = exception;
            _bytesTransferred = bytesTransferred;
            _socketFlags = flags;

            if (exception == null)
            {
                _socketError = SocketError.Success;
            }
            else
            {
                SocketException socketException = exception as SocketException;
                if (socketException != null)
                {
                    _socketError = socketException.SocketErrorCode;
                }
                else
                {
                    _socketError = SocketError.SocketError;
                }
            }
        }

        private static void ExecutionCallback(object state)
        {
            var thisRef = (SocketAsyncEventArgs)state;
            thisRef.OnCompleted(thisRef);
        }

        // Marks this object as no longer "in-use". Will also execute a Dispose deferred
        // because I/O was in progress.  
        internal void Complete()
        {
            // Mark as not in-use.
            _operating = Free;

            InnerComplete();

            // Check for deferred Dispose().
            // The deferred Dispose is not guaranteed if Dispose is called while an operation is in progress. 
            // The _disposeCalled variable is not managed in a thread-safe manner on purpose for performance.
            if (_disposeCalled)
            {
                Dispose();
            }
        }

        // Dispose call to implement IDisposable.
        public void Dispose()
        {
            // Remember that Dispose was called.
            _disposeCalled = true;

            // Check if this object is in-use for an async socket operation.
            if (Interlocked.CompareExchange(ref _operating, Disposed, Free) != Free)
            {
                // Either already disposed or will be disposed when current operation completes.
                return;
            }

            // OK to dispose now.
            FreeInternals(false);

            // Don't bother finalizing later.
            GC.SuppressFinalize(this);
        }

        ~SocketAsyncEventArgs()
        {
            FreeInternals(true);
        }

        // NOTE: Use a try/finally to make sure Complete is called when you're done
        private void StartConfiguring()
        {
            int status = Interlocked.CompareExchange(ref _operating, Configuring, Free);
            if (status == InProgress || status == Configuring)
            {
                throw new InvalidOperationException(SR.net_socketopinprogress);
            }
            else if (status == Disposed)
            {
                throw new ObjectDisposedException(GetType().FullName);
            }
        }

        // Prepares for a native async socket call.
        // This method performs the tasks common to all socket operations.
        internal void StartOperationCommon(Socket socket)
        {
            // Change status to "in-use".
            if (Interlocked.CompareExchange(ref _operating, InProgress, Free) != Free)
            {
                // If it was already "in-use" check if Dispose was called.
                if (_disposeCalled)
                {
                    // Dispose was called - throw ObjectDisposed.
                    throw new ObjectDisposedException(GetType().FullName);
                }

                // Only one at a time.
                throw new InvalidOperationException(SR.net_socketopinprogress);
            }

            // Prepare execution context for callback.
            // If event delegates have changed or socket has changed
            // then discard any existing context.
            if (_completedChanged || socket != _currentSocket)
            {
                _completedChanged = false;
                _context = null;
            }

            // Capture execution context if none already.
            if (_context == null)
            {
                _context = ExecutionContext.Capture();
            }

            // Remember current socket.
            _currentSocket = socket;
        }

        internal void StartOperationAccept()
        {
            // Remember the operation type.
            _completedOperation = SocketAsyncOperation.Accept;

            // AcceptEx needs a single buffer with room for two special sockaddr data structures.
            // 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.

            // First calculate the special AcceptEx address buffer size.
            // It is the size of two native sockaddr buffers with 16 extra bytes each.
            // The native sockaddr buffers vary by address family so must reference the current socket.
            _acceptAddressBufferCount = 2 * (_currentSocket._rightEndPoint.Serialize().Size + 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.
            // Throw if that buffer is not large enough.  
            bool userSuppliedBuffer = _buffer != null;
            if (userSuppliedBuffer)
            {
                // Caller specified a buffer - see if it is large enough
                if (_count < _acceptAddressBufferCount)
                {
                    throw new ArgumentException(SR.Format(SR.net_buffercounttoosmall, "Count"));
                }

                // Buffer is already pinned if necessary.
            }
            else
            {
                // Caller didn't specify a buffer so use an internal one.
                // See if current internal one is big enough, otherwise create a new one.
                if (_acceptBuffer == null || _acceptBuffer.Length < _acceptAddressBufferCount)
                {
                    _acceptBuffer = new byte[_acceptAddressBufferCount];
                }
            }

            InnerStartOperationAccept(userSuppliedBuffer);
        }

        internal void StartOperationConnect()
        {
            // Remember the operation type.
            _completedOperation = SocketAsyncOperation.Connect;
            _multipleConnect = null;
            _connectSocket = null;

            InnerStartOperationConnect();
        }

        internal void StartOperationWrapperConnect(MultipleConnectAsync args)
        {
            _completedOperation = SocketAsyncOperation.Connect;
            _multipleConnect = args;
            _connectSocket = null;
        }

        internal void CancelConnectAsync()
        {
            if (_operating == InProgress && _completedOperation == SocketAsyncOperation.Connect)
            {
                if (_multipleConnect != null)
                {
                    // If a multiple connect is in progress, abort it.
                    _multipleConnect.Cancel();
                }
                else
                {
                    // Otherwise we're doing a normal ConnectAsync - cancel it by closing the socket.
                    // _currentSocket will only be null if _multipleConnect was set, so we don't have to check.
                    if (_currentSocket == null)
                    {
                        if (GlobalLog.IsEnabled)
                        {
                            GlobalLog.Assert("SocketAsyncEventArgs::CancelConnectAsync - CurrentSocket and MultipleConnect both null!");
                        }
                        Debug.Fail("SocketAsyncEventArgs::CancelConnectAsync - CurrentSocket and MultipleConnect both null!");
                    }
                    _currentSocket.Dispose();
                }
            }
        }

        internal void StartOperationDisconnect()
        {
            // Remember the operation type.
            _completedOperation = SocketAsyncOperation.Disconnect;
            InnerStartOperationDisconnect();
        }

        internal void StartOperationReceive()
        {
            // Remember the operation type.
            _completedOperation = SocketAsyncOperation.Receive;
            InnerStartOperationReceive();
        }

        internal void StartOperationReceiveFrom()
        {
            // Remember the operation type.
            _completedOperation = SocketAsyncOperation.ReceiveFrom;
            InnerStartOperationReceiveFrom();
        }

        internal void StartOperationReceiveMessageFrom()
        {
            // Remember the operation type.
            _completedOperation = SocketAsyncOperation.ReceiveMessageFrom;
            InnerStartOperationReceiveMessageFrom();
        }

        internal void StartOperationSend()
        {
            // Remember the operation type.
            _completedOperation = SocketAsyncOperation.Send;
            InnerStartOperationSend();
        }

        internal void StartOperationSendPackets()
        {
            // Remember the operation type.
            _completedOperation = SocketAsyncOperation.SendPackets;
            InnerStartOperationSendPackets();
        }

        internal void StartOperationSendTo()
        {
            // Remember the operation type.
            _completedOperation = SocketAsyncOperation.SendTo;
            InnerStartOperationSendTo();
        }

        internal void UpdatePerfCounters(int size, bool sendOp)
        {
            if (sendOp)
            {
                SocketPerfCounter.Instance.Increment(SocketPerfCounterName.SocketBytesSent, size);
                if (_currentSocket.Transport == TransportType.Udp)
                {
                    SocketPerfCounter.Instance.Increment(SocketPerfCounterName.SocketDatagramsSent);
                }
            }
            else
            {
                SocketPerfCounter.Instance.Increment(SocketPerfCounterName.SocketBytesReceived, size);
                if (_currentSocket.Transport == TransportType.Udp)
                {
                    SocketPerfCounter.Instance.Increment(SocketPerfCounterName.SocketDatagramsReceived);
                }
            }
        }

        internal void FinishOperationSyncFailure(SocketError socketError, int bytesTransferred, SocketFlags flags)
        {
            SetResults(socketError, bytesTransferred, flags);

            // This will be null if we're doing a static ConnectAsync to a DnsEndPoint with AddressFamily.Unspecified;
            // the attempt socket will be closed anyways, so not updating the state is OK.
            if (_currentSocket != null)
            {
                _currentSocket.UpdateStatusAfterSocketError(socketError);
            }

            Complete();
        }

        internal void FinishConnectByNameSyncFailure(Exception exception, int bytesTransferred, SocketFlags flags)
        {
            SetResults(exception, bytesTransferred, flags);

            if (_currentSocket != null)
            {
                _currentSocket.UpdateStatusAfterSocketError(_socketError);
            }

            Complete();
        }

        internal void FinishOperationAsyncFailure(SocketError socketError, int bytesTransferred, SocketFlags flags)
        {
            SetResults(socketError, bytesTransferred, flags);

            // This will be null if we're doing a static ConnectAsync to a DnsEndPoint with AddressFamily.Unspecified;
            // the attempt socket will be closed anyways, so not updating the state is OK.
            if (_currentSocket != null)
            {
                _currentSocket.UpdateStatusAfterSocketError(socketError);
            }

            Complete();
            if (_context == null)
            {
                OnCompleted(this);
            }
            else
            {
                ExecutionContext.Run(_context, s_executionCallback, this);
            }
        }

        internal void FinishOperationAsyncFailure(Exception exception, int bytesTransferred, SocketFlags flags)
        {
            SetResults(exception, bytesTransferred, flags);

            if (_currentSocket != null)
            {
                _currentSocket.UpdateStatusAfterSocketError(_socketError);
            }

            Complete();
            if (_context == null)
            {
                OnCompleted(this);
            }
            else
            {
                ExecutionContext.Run(_context, s_executionCallback, this);
            }
        }

        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.
            Complete();
            if (_context == null)
            {
                OnCompleted(this);
            }
            else
            {
                ExecutionContext.Run(_context, s_executionCallback, this);
            }
        }

        internal void FinishOperationSuccess(SocketError socketError, int bytesTransferred, SocketFlags flags)
        {
            SetResults(socketError, bytesTransferred, flags);

            switch (_completedOperation)
            {
                case SocketAsyncOperation.Accept:
                    if (bytesTransferred > 0)
                    {
                        // Log and Perf counters.
                        if (s_loggingEnabled)
                        {
                            LogBuffer(bytesTransferred);
                        }
                        if (Socket.s_perfCountersEnabled)
                        {
                            UpdatePerfCounters(bytesTransferred, false);
                        }
                    }

                    // Get the endpoint.
                    Internals.SocketAddress remoteSocketAddress = IPEndPointExtensions.Serialize(_currentSocket._rightEndPoint);

                    socketError = FinishOperationAccept(remoteSocketAddress);

                    if (socketError == SocketError.Success)
                    {
                        _acceptSocket = _currentSocket.UpdateAcceptSocket(_acceptSocket, _currentSocket._rightEndPoint.Create(remoteSocketAddress));

                        if (s_loggingEnabled)
                            SocketsEventSource.Accepted(_acceptSocket, _acceptSocket.RemoteEndPoint, _acceptSocket.LocalEndPoint);
                    }
                    else
                    {
                        SetResults(socketError, bytesTransferred, SocketFlags.None);
                        _acceptSocket = null;
                    }
                    break;

                case SocketAsyncOperation.Connect:
                    if (bytesTransferred > 0)
                    {
                        // Log and Perf counters.
                        if (s_loggingEnabled)
                        {
                            LogBuffer(bytesTransferred);
                        }
                        if (Socket.s_perfCountersEnabled)
                        {
                            UpdatePerfCounters(bytesTransferred, true);
                        }
                    }

                    socketError = FinishOperationConnect();

                    // Mark socket connected.
                    if (socketError == SocketError.Success)
                    {
                        if (s_loggingEnabled)
                            SocketsEventSource.Connected(_currentSocket, _currentSocket.LocalEndPoint, _currentSocket.RemoteEndPoint);

                        _currentSocket.SetToConnected();
                        _connectSocket = _currentSocket;
                    }
                    break;

                case SocketAsyncOperation.Disconnect:
                    _currentSocket.SetToDisconnected();
                    _currentSocket._remoteEndPoint = null;

                    break;

                case SocketAsyncOperation.Receive:
                    if (bytesTransferred > 0)
                    {
                        // Log and Perf counters.
                        if (s_loggingEnabled)
                        {
                            LogBuffer(bytesTransferred);
                        }
                        if (Socket.s_perfCountersEnabled)
                        {
                            UpdatePerfCounters(bytesTransferred, false);
                        }
                    }
                    break;

                case SocketAsyncOperation.ReceiveFrom:
                    if (bytesTransferred > 0)
                    {
                        // Log and Perf counters.
                        if (s_loggingEnabled)
                        {
                            LogBuffer(bytesTransferred);
                        }
                        if (Socket.s_perfCountersEnabled)
                        {
                            UpdatePerfCounters(bytesTransferred, false);
                        }
                    }

                    // Deal with incoming address.
                    _socketAddress.InternalSize = GetSocketAddressSize();
                    Internals.SocketAddress socketAddressOriginal = IPEndPointExtensions.Serialize(_remoteEndPoint);
                    if (!socketAddressOriginal.Equals(_socketAddress))
                    {
                        try
                        {
                            _remoteEndPoint = _remoteEndPoint.Create(_socketAddress);
                        }
                        catch
                        {
                        }
                    }
                    break;

                case SocketAsyncOperation.ReceiveMessageFrom:
                    if (bytesTransferred > 0)
                    {
                        // Log and Perf counters.
                        if (s_loggingEnabled)
                        {
                            LogBuffer(bytesTransferred);
                        }
                        if (Socket.s_perfCountersEnabled)
                        {
                            UpdatePerfCounters(bytesTransferred, false);
                        }
                    }

                    // Deal with incoming address.
                    _socketAddress.InternalSize = GetSocketAddressSize();
                    socketAddressOriginal = IPEndPointExtensions.Serialize(_remoteEndPoint);
                    if (!socketAddressOriginal.Equals(_socketAddress))
                    {
                        try
                        {
                            _remoteEndPoint = _remoteEndPoint.Create(_socketAddress);
                        }
                        catch
                        {
                        }
                    }

                    FinishOperationReceiveMessageFrom();
                    break;

                case SocketAsyncOperation.Send:
                    if (bytesTransferred > 0)
                    {
                        // Log and Perf counters.
                        if (s_loggingEnabled)
                        {
                            LogBuffer(bytesTransferred);
                        }
                        if (Socket.s_perfCountersEnabled)
                        {
                            UpdatePerfCounters(bytesTransferred, true);
                        }
                    }
                    break;

                case SocketAsyncOperation.SendPackets:
                    if (bytesTransferred > 0)
                    {
                        // Log and Perf counters.
                        if (s_loggingEnabled)
                        {
                            LogSendPacketsBuffers(bytesTransferred);
                        }
                        if (Socket.s_perfCountersEnabled)
                        {
                            UpdatePerfCounters(bytesTransferred, true);
                        }
                    }

                    FinishOperationSendPackets();
                    break;

                case SocketAsyncOperation.SendTo:
                    if (bytesTransferred > 0)
                    {
                        // Log and Perf counters.
                        if (s_loggingEnabled)
                        {
                            LogBuffer(bytesTransferred);
                        }
                        if (Socket.s_perfCountersEnabled)
                        {
                            UpdatePerfCounters(bytesTransferred, true);
                        }
                    }
                    break;
            }

            if (socketError != SocketError.Success)
            {
                // Asynchronous failure or something went wrong after async success.
                SetResults(socketError, bytesTransferred, flags);
                _currentSocket.UpdateStatusAfterSocketError(socketError);
            }

            // Complete the operation and raise completion event.
            Complete();
            if (_context == null)
            {
                OnCompleted(this);
            }
            else
            {
                ExecutionContext.Run(_context, s_executionCallback, this);
            }
        }
    }
}