File: ProcessMessagesAsyncResult.cs

package info (click to toggle)
mono 6.12.0.199%2Bdfsg-6
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 1,296,836 kB
  • sloc: cs: 11,181,803; xml: 2,850,076; ansic: 699,709; cpp: 123,344; perl: 59,361; javascript: 30,841; asm: 21,853; makefile: 20,405; sh: 15,009; python: 4,839; pascal: 925; sql: 859; sed: 16; php: 1
file content (806 lines) | stat: -rw-r--r-- 30,490 bytes parent folder | download | duplicates (7)
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
//----------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
//----------------------------------------------------------------

namespace System.ServiceModel.Routing
{
    using System;
    using System.Configuration;
    using System.Globalization;
    using System.Runtime;
    using System.ServiceModel.Channels;
    using System.ServiceModel.Description;
    using System.ServiceModel.Dispatcher;
    using System.ServiceModel.Security;
    using System.Transactions;

    class ProcessMessagesAsyncResult<TContract> : TransactedAsyncResult
    {
        static AsyncCompletion clientOperationCallback = ClientOperationCallback;
        static AsyncCompletion completeReceiveContextCallback = CompleteReceiveContextCallback;
        static AsyncCompletion commitTransactionCallback = CommitTransactionCallback;
        static AsyncCompletion channelCloseCallback = ChannelCloseCallback;
        
        bool abortedRetry;
        bool allCompletedSync = true;
        RoutingChannelExtension channelExtension;
        IRoutingClient client;
        bool closeOutboundChannels;
        int destinationIndex;
        RoutingService service;
        int sessionMessageIndex;
        ProcessingState state = ProcessingState.Initial;
        TimeoutHelper timeoutHelper;

        public ProcessMessagesAsyncResult(Message message, RoutingService service, TimeSpan timeout, AsyncCallback callback, object state)
            : base(callback, state)
        {
            this.service = service;
            this.channelExtension = service.ChannelExtension;
            this.timeoutHelper = new TimeoutHelper(timeout);
            this.timeoutHelper.RemainingTime(); //Start the timer

            if (message == null)
            {
                //Null message means end of session, time to close everything
                this.closeOutboundChannels = true;
                this.state = ProcessingState.ClosingChannels;
            }
            else
            {
                this.closeOutboundChannels = false;
                MessageRpc messageRpc = new MessageRpc(message, OperationContext.Current, this.channelExtension.ImpersonationRequired);
                if (TD.RoutingServiceProcessingMessageIsEnabled())
                {
                    TD.RoutingServiceProcessingMessage(messageRpc.EventTraceActivity, messageRpc.UniqueID, messageRpc.Message.Headers.Action, messageRpc.OperationContext.EndpointDispatcher.EndpointAddress.Uri.ToString(), (messageRpc.Transaction != null).ToString());
                }

                EndpointNameMessageFilter.Set(messageRpc.Message.Properties, this.channelExtension.EndpointName);
                messageRpc.RouteToEndpoints<TContract>(this.service.RoutingConfig);
                this.service.SessionMessages.Add(messageRpc);

                this.sessionMessageIndex = this.service.SessionMessages.Count - 1;
                if (this.sessionMessageIndex == 0)
                {
                    //First message, do initialization stuff
                    this.state = ProcessingState.Initial;
                }
                else
                {
                    this.state = ProcessingState.SendingSessionMessages;
                }
            }
            this.ProcessWhileSync();
        }

        void ProcessWhileSync()
        {
            try
            {
                bool callAgain;
                do
                {
                    callAgain = this.ProcessNext();
                } while (callAgain);
            }
            catch (Exception e)
            {
                if (Fx.IsFatal(e))
                {
                    throw;
                }

                this.Fault(e);
            }
        }

        void ChangeState(ProcessingState newState)
        {
            this.sessionMessageIndex = 0;
            this.destinationIndex = 0;
            this.state = newState;
        }

        void ResetState()
        {
            this.service.ResetSession();
            this.ChangeState(ProcessingState.Initial);
        }

        bool ProcessNext()
        {
            switch (this.state)
            {
                case ProcessingState.Initial:
                    {
                        this.service.CreateNewTransactionIfNeeded(this.service.SessionMessages[0]);
                        return this.DoneInitializing();
                    }

                case ProcessingState.SendingSessionMessages:
                    {
                        return this.SendToCurrentClient();
                    }

                case ProcessingState.ClosingChannels:
                    {
                        return this.CloseCurrentChannel();
                    }

                case ProcessingState.CompletingReceiveContexts:
                    {
                        return this.CompleteCurrentReceiveContext();
                    }

                case ProcessingState.CommittingTransaction:
                    {
                        return this.CommitTransaction();
                    }

                case ProcessingState.Completing:
                    {
                        this.CompleteSelf(null);
                        return false;
                    }

                default:
                    Fx.Assert("ProcessNext shouldn't be called in this state: " + this.state);
                    return false;
            }
        }

        bool SendToCurrentClient()
        {
            MessageRpc messageRpc = this.service.SessionMessages[this.sessionMessageIndex];
            SendOperation sendOperation = messageRpc.Operations[this.destinationIndex];
            if (sendOperation.Sent)
            {
                this.MoveToNextClientOperation(messageRpc.Operations.Count);
                return true;
            }
            else if (!this.channelExtension.ReceiveContextEnabled &&
                this.channelExtension.TransactedReceiveEnabled &&
                sendOperation.HasAlternate)
            {
                // We can't do error handling for oneway Transactional unless there's RC.
                throw FxTrace.Exception.AsError(new ConfigurationErrorsException(SR.ErrorHandlingNotSupportedTxNoRC(messageRpc.OperationContext.Channel.LocalAddress)));
            }

            RoutingEndpointTrait endpointTrait = sendOperation.CurrentEndpoint;
            this.client = this.service.GetOrCreateClient<TContract>(endpointTrait, messageRpc.Impersonating);
            try
            {
                // We always work on cloned message when there are backup endpoints to handle exception cases
                Message message;
                if (messageRpc.Operations.Count == 1 && sendOperation.AlternateEndpointCount == 0)
                {
                    message = messageRpc.Message;
                }
                else
                {
                    message = messageRpc.CreateBuffer().CreateMessage();
                }

                sendOperation.PrepareMessage(message);
                IAsyncResult result;

                if (TD.RoutingServiceTransmittingMessageIsEnabled())
                {
                    TD.RoutingServiceTransmittingMessage(messageRpc.EventTraceActivity, messageRpc.UniqueID, this.destinationIndex.ToString(TD.Culture), this.client.Key.ToString());
                }

                Transaction transaction = this.service.GetTransactionForSending(messageRpc);
                using (this.PrepareTransactionalCall(transaction))
                {
                    IDisposable impersonationContext = null;
                    try
                    {
                        //Perform the assignment in a finally block so it won't be interrupted asynchronously
                        try { } 
                        finally
                        {
                            impersonationContext = messageRpc.PrepareCall();
                        }
                        
                        result = this.client.BeginOperation(message, transaction, this.PrepareAsyncCompletion(clientOperationCallback), this);
                    }
                    finally
                    {
                        if (impersonationContext != null)
                        {
                            impersonationContext.Dispose();
                        }
                    }
                }

                if (this.CheckSyncContinue(result))
                {
                    this.ClientOperationComplete(result);
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception exception)
            {
                if (Fx.IsFatal(exception))
                {
                    throw;
                }

                //See if we can handle this Exception...
                if (this.HandleClientOperationFailure(exception))
                {
                    return true;
                }
                throw;
            }
        }

        static bool ClientOperationCallback(IAsyncResult result)
        {
            ProcessMessagesAsyncResult<TContract> thisPtr = (ProcessMessagesAsyncResult<TContract>)result.AsyncState;
            FxTrace.Trace.SetAndTraceTransfer(thisPtr.channelExtension.ActivityID, true);
            try
            {
                try
                {
                    thisPtr.allCompletedSync = false;
                    thisPtr.ClientOperationComplete(result);
                }
                catch (Exception exception)
                {
                    if (Fx.IsFatal(exception))
                    {
                        throw;
                    }

                    //See if we can handle this Exception...
                    if (!thisPtr.HandleClientOperationFailure(exception))
                    {
                        throw;
                    }
                }

                thisPtr.ProcessWhileSync();
            }
            catch (Exception e)
            {
                if (Fx.IsFatal(e))
                {
                    throw;
                }

                thisPtr.Fault(e);
            }

            return false;
        }

        void ClientOperationComplete(IAsyncResult result)
        {
            MessageRpc messageRpc = this.service.SessionMessages[this.sessionMessageIndex];
            SendOperation currentDest = messageRpc.Operations[this.destinationIndex];

            this.client.EndOperation(result);
            currentDest.TransmitSucceeded(this.service.GetTransactionForSending(messageRpc));

            if (TD.RoutingServiceTransmitSucceededIsEnabled())
            {
                TD.RoutingServiceTransmitSucceeded(messageRpc.EventTraceActivity, messageRpc.UniqueID, this.destinationIndex.ToString(TD.Culture), currentDest.CurrentEndpoint.ToString());
            }
            MoveToNextClientOperation(messageRpc.Operations.Count);
        }

        void MoveToNextClientOperation(int operationCount)
        {
            if (++this.destinationIndex >= operationCount)
            {
                //We've processed all multicasts for a given MessageRpc, move on to the next message (if any)
                this.destinationIndex = 0;

                // If we're one-way non-transactional and non-ReceiveContext then
                // we don't need to store messages for session replay or RC.Complete
                if (!this.channelExtension.ReceiveContextEnabled && !this.channelExtension.TransactedReceiveEnabled)
                {
                    this.service.SessionMessages.RemoveAt(this.sessionMessageIndex);
                    --this.sessionMessageIndex;
                }

                if (++this.sessionMessageIndex >= this.service.SessionMessages.Count)
                {
                    this.DoneSendingMessages();
                }
            }
        }

        void AbandonReceiveContexts()
        {
            if (this.channelExtension.ReceiveContextEnabled)
            {
                foreach (MessageRpc messageRpc in this.service.SessionMessages)
                {
                    try
                    {
                        if (TD.RoutingServiceAbandoningReceiveContextIsEnabled())
                        {
                            TD.RoutingServiceAbandoningReceiveContext(messageRpc.EventTraceActivity, messageRpc.UniqueID);
                        }
                        messageRpc.ReceiveContext.Abandon(this.timeoutHelper.RemainingTime());
                    }
                    catch (Exception e)
                    {
                        if (Fx.IsFatal(e))
                        {
                            throw;
                        }

                        if (TD.RoutingServiceHandledExceptionIsEnabled())
                        {
                            TD.RoutingServiceHandledException(messageRpc.EventTraceActivity, e);
                        }
                    }
                }
            }
        }

        bool DoneClosingChannels()
        {
            if (this.channelExtension.ReceiveContextEnabled)
            {
                this.ChangeState(ProcessingState.CompletingReceiveContexts);
            }
            else if (this.service.RetryTransaction != null || this.channelExtension.TransactedReceiveEnabled)
            {
                this.ChangeState(ProcessingState.CommittingTransaction);
            }
            else
            {
                this.ChangeState(ProcessingState.Completing);
            }
            return true;
        }

        bool DoneCommittingTransaction()
        {
            this.ChangeState(ProcessingState.Completing);
            return true;
        }

        bool DoneCompletingReceiveContexts()
        {
            if (this.service.RetryTransaction != null || this.channelExtension.TransactedReceiveEnabled)
            {
                this.ChangeState(ProcessingState.CommittingTransaction);
            }
            else
            {
                this.ChangeState(ProcessingState.Completing);
            }
            return true;
        }

        bool DoneInitializing()
        {
            this.ChangeState(ProcessingState.SendingSessionMessages);
            return true;
        }

        bool DoneSendingMessages()
        {
            if (this.closeOutboundChannels)
            {
                this.ChangeState(ProcessingState.ClosingChannels);
            }
            else if (this.channelExtension.HasSession)
            {
                this.ChangeState(ProcessingState.Completing);
            }
            else if (this.channelExtension.ReceiveContextEnabled)
            {
                this.ChangeState(ProcessingState.CompletingReceiveContexts);
            }
            else if (this.service.RetryTransaction != null || this.channelExtension.TransactedReceiveEnabled)
            {
                this.ChangeState(ProcessingState.CommittingTransaction);
            }
            else
            {
                this.ChangeState(ProcessingState.Completing);
            }
            return true;
        }

        bool CloseCurrentChannel()
        {
            this.client = this.channelExtension.SessionChannels.ReleaseChannel();
            
            if (this.client == null)
            {
                return this.DoneClosingChannels();
            }

            try
            {
                if (TD.RoutingServiceClosingClientIsEnabled())
                {
                    TD.RoutingServiceClosingClient(this.client.Key.ToString());
                }
                IAsyncResult result;
                using (this.PrepareTransactionalCall(this.service.GetTransactionForSending(null)))
                {
                    result = ((ICommunicationObject)this.client).BeginClose(this.timeoutHelper.RemainingTime(),
                        this.PrepareAsyncCompletion(channelCloseCallback), this);
                }

                if (this.CheckSyncContinue(result))
                {
                    this.ChannelCloseComplete(result);
                    return true;
                }
                return false;
            }
            catch (Exception exception)
            {
                if (this.HandleCloseFailure(exception))
                {
                    return true;
                }
                throw;
            }
        }

        static bool ChannelCloseCallback(IAsyncResult result)
        {
            ProcessMessagesAsyncResult<TContract> thisPtr = (ProcessMessagesAsyncResult<TContract>)result.AsyncState;
            FxTrace.Trace.SetAndTraceTransfer(thisPtr.channelExtension.ActivityID, true);
            try
            {
                thisPtr.allCompletedSync = false;
                try
                {
                    thisPtr.ChannelCloseComplete(result);
                }
                catch (Exception exception)
                {
                    if (!thisPtr.HandleCloseFailure(exception))
                    {
                        throw;
                    }
                }

                thisPtr.ProcessWhileSync();
            }
            catch (Exception e)
            {
                if (Fx.IsFatal(e))
                {
                    throw;
                }

                thisPtr.Fault(e);
            }
            return false;
        }

        void ChannelCloseComplete(IAsyncResult result)
        {
            ((ICommunicationObject)this.client).EndClose(result);
        }

        bool HandleClientOperationFailure(Exception e)
        {
            if (TD.RoutingServiceTransmitFailedIsEnabled())
            {
                TD.RoutingServiceTransmitFailed(null, this.client.Key.ToString(), e);
            }

            if (!(e is CommunicationException || e is TimeoutException))
            {
                //We only move to backup for CommunicationExceptions and TimeoutExceptions
                return false;
            }

            bool canHandle;
            MessageRpc messageRpc = this.service.SessionMessages[this.sessionMessageIndex];
            SendOperation sendOperation = messageRpc.Operations[this.destinationIndex];

            if ((e is CommunicationObjectAbortedException || e is CommunicationObjectFaultedException) && 
                !this.channelExtension.HasSession)
            {
                // Messages on a non sessionful channel share outbound connections and can 
                // fail due to other messages failing on the same channel
                bool canRetry = (this.channelExtension.ReceiveContextEnabled || !this.channelExtension.TransactedReceiveEnabled);
                if (canRetry && !this.abortedRetry)
                {
                    //No session and ReceiveContext or non transactional, retry the message 1 time (before moving to backup)
                    this.abortedRetry = true;
                    this.ResetState();
                    return true;
                }
            }
            else if (e is EndpointNotFoundException)
            {
                // The channel may not fault for this exception for bindings other than netTcpBinding
                // We abort the channel in that case. We proactively clean up so that we don't have to cleanup later
                SessionChannels sessionChannels = this.service.GetSessionChannels(messageRpc.Impersonating);
                if (sessionChannels != null)
                {
                    sessionChannels.AbortChannel(sendOperation.CurrentEndpoint);
                }
            }
            else if (e is MessageSecurityException)
            {
                // The service may have been stopped and restarted without the routing service knowledge.
                // When we try to use a cached channel to the service, the channel can fault due to this exception
                // The faulted channel gets cleaned up and we retry one more time only when service has backup
                // If there is no backup, we do not retry since we do not create a buffered message to prevent performance degradation
                if (!this.abortedRetry && (sendOperation.AlternateEndpointCount > 0))
                {
                    this.abortedRetry = true;
                    this.ResetState();
                    return true;
                }
            }

            if (sendOperation.TryMoveToAlternate(e))
            {
                if (TD.RoutingServiceMovedToBackupIsEnabled())
                {
                    TD.RoutingServiceMovedToBackup(messageRpc.EventTraceActivity, messageRpc.UniqueID, this.destinationIndex.ToString(TD.Culture), sendOperation.CurrentEndpoint.ToString());
                }
                this.ResetState();
                canHandle = true; 
            }
            else if (this.service.GetTransactionForSending(messageRpc) == null)
            {
                // This is OneWay with no Transaction...
                // store this exception for when we complete, but continue any multicasting
                this.service.SessionException = e;
                
                // Mark the SendOperation as 'Sent' because there's no more work we can do (non-tx and no more backups)
                sendOperation.TransmitSucceeded(null);

                if (this.channelExtension.HasSession)
                {
                    this.channelExtension.SessionChannels.AbortChannel(this.client.Key);
                }

                this.MoveToNextClientOperation(messageRpc.Operations.Count);
                canHandle = true;
            }
            else
            {
                canHandle = false;
            }

            return canHandle;
        }

        // A Sessionful channel failed when closing, find all messages that went on that 
        // session/channel and move them to their backup endpoints
        bool HandleCloseFailure(Exception e)
        {
            if (!(e is CommunicationException || e is TimeoutException))
            {
                return false;
            }

            if (TD.RoutingServiceCloseFailedIsEnabled())
            {
                TD.RoutingServiceCloseFailed(this.client.Key.ToString(), e);
            }
            this.channelExtension.SessionChannels.AbortChannel(this.client.Key);

            if (this.service.SessionMessages.Count == 0)
            {
                //All messages have been sent and we're non-transactional
                Fx.Assert(!this.service.ChannelExtension.TransactedReceiveEnabled, "Should only happen for non-transactional cases");
                return true;
            }

            foreach (MessageRpc messageRpc in this.service.SessionMessages)
            {
                for (this.destinationIndex = 0; this.destinationIndex < messageRpc.Operations.Count; this.destinationIndex++)
                {
                    SendOperation sendOperation = messageRpc.Operations[this.destinationIndex];
                    if (client.Key.Equals(sendOperation.CurrentEndpoint))
                    {
                        if (!sendOperation.TryMoveToAlternate(e))
                        {
                            return false;
                        }
                        if (TD.RoutingServiceMovedToBackupIsEnabled())
                        {
                            TD.RoutingServiceMovedToBackup(messageRpc.EventTraceActivity, messageRpc.UniqueID, this.destinationIndex.ToString(TD.Culture), sendOperation.CurrentEndpoint.ToString());
                        }
                    }
                }
            }

            this.ResetState();
            return true;
        }

        bool CompleteCurrentReceiveContext()
        {
            if (this.service.SessionException != null)
            {
                //This means at least one multicast branch did not reach any of the configured endpoints
                this.Fault(this.service.SessionException);
                return false;
            }

            bool keepGoing;
            MessageRpc messageRpc = this.service.SessionMessages[this.sessionMessageIndex];
            if (messageRpc.ReceiveContext != null)
            {
                if (TD.RoutingServiceCompletingReceiveContextIsEnabled())
                {
                    TD.RoutingServiceCompletingReceiveContext(messageRpc.EventTraceActivity, messageRpc.UniqueID);
                }

                IAsyncResult result;
                using (this.PrepareTransactionalCall(this.service.GetTransactionForSending(messageRpc)))
                {
                    result = messageRpc.ReceiveContext.BeginComplete(this.timeoutHelper.RemainingTime(),
                        this.PrepareAsyncCompletion(completeReceiveContextCallback), this);
                }
                if (this.CheckSyncContinue(result))
                {
                    keepGoing = this.CompleteReceiveContextCompleted(result);
                }
                else
                {
                    keepGoing = false;
                }
            }
            else
            {
                // Either all messages have RC or all messages don't have RC.  Since we don't have one
                // we know that none of these messages will, so we don't have to look at the other messages
                Fx.Assert("We shouldn't enter CompletingReceiveContexts state if the binding is not ReceiveContext capable");
                keepGoing = this.DoneCompletingReceiveContexts();
            }

            return keepGoing;
        }

        static bool CompleteReceiveContextCallback(IAsyncResult result)
        {
            ProcessMessagesAsyncResult<TContract> thisPtr = (ProcessMessagesAsyncResult<TContract>)result.AsyncState;
            FxTrace.Trace.SetAndTraceTransfer(thisPtr.channelExtension.ActivityID, true);
            try
            {
                thisPtr.allCompletedSync = false;
                if (thisPtr.CompleteReceiveContextCompleted(result))
                {
                    thisPtr.ProcessWhileSync();
                }
            }
            catch (Exception e)
            {
                if (Fx.IsFatal(e))
                {
                    throw;
                }
                thisPtr.Fault(e);
            }
            return false;
        }

        bool CompleteReceiveContextCompleted(IAsyncResult result)
        {
            MessageRpc messageRpc = this.service.SessionMessages[this.sessionMessageIndex];
            messageRpc.ReceiveContext.EndComplete(result);

            if (++this.sessionMessageIndex >= this.service.SessionMessages.Count)
            {
                return this.DoneCompletingReceiveContexts();
            }
            return true;
        }

        bool CommitTransaction()
        {
            if (this.service.RetryTransaction != null)
            {
                if (TD.RoutingServiceCommittingTransactionIsEnabled())
                {
                    TD.RoutingServiceCommittingTransaction(this.service.RetryTransaction.TransactionInformation.LocalIdentifier);
                }

                IAsyncResult result = this.service.RetryTransaction.BeginCommit(
                    this.PrepareAsyncCompletion(commitTransactionCallback), this);
                if (this.CheckSyncContinue(result))
                {
                    return this.CommitTransactionCompleted(result);
                }
                return false;
            }
            else if (this.channelExtension.TransactedReceiveEnabled)
            {
                if (TD.RoutingServiceCommittingTransactionIsEnabled())
                {
                    Transaction transaction = this.service.GetTransactionForSending(null);
                    TD.RoutingServiceCommittingTransaction(transaction != null ? transaction.TransactionInformation.LocalIdentifier : string.Empty);
                }
            }

            return this.DoneCommittingTransaction();
        }

        static bool CommitTransactionCallback(IAsyncResult result)
        {
            ProcessMessagesAsyncResult<TContract> thisPtr = (ProcessMessagesAsyncResult<TContract>)result.AsyncState;
            FxTrace.Trace.SetAndTraceTransfer(thisPtr.channelExtension.ActivityID, true);
            try
            {
                thisPtr.allCompletedSync = false;
                if (thisPtr.CommitTransactionCompleted(result))
                {
                    thisPtr.ProcessWhileSync();
                }
            }
            catch (Exception e)
            {
                if (Fx.IsFatal(e))
                {
                    throw;
                }
                thisPtr.Fault(e);
            }
            return false;
        }

        bool CommitTransactionCompleted(IAsyncResult result)
        {
            this.service.RetryTransaction.EndCommit(result);
            return this.DoneCommittingTransaction();
        }

        void CompleteSelf(Exception operationException)
        {
            Exception exception = operationException;
            if (exception == null && (this.closeOutboundChannels || !this.channelExtension.HasSession))
            {
                // It's possible that this last operation in a session didn't result in an exception
                // but we still have an exception to report when closing the session...
                exception = this.service.SessionException;
            }

            if (!this.closeOutboundChannels)
            {
                //When we're closing the channels that means end of session, there's no message per se.
                if (TD.RoutingServiceCompletingOneWayIsEnabled()) { TD.RoutingServiceCompletingOneWay(exception); }
            }
            this.Complete(this.allCompletedSync, exception);
        }

        internal static void End(IAsyncResult result)
        {
            AsyncResult.End<ProcessMessagesAsyncResult<TContract>>(result);
        }

        void Fault(Exception e)
        {
            this.service.ResetSession();
            this.AbandonReceiveContexts();

            this.CompleteSelf(e);
        }

        enum ProcessingState
        {
            Initial = 0,
            SendingSessionMessages,
            ClosingChannels,
            CompletingReceiveContexts,
            CommittingTransaction,
            Completing,
            Completed
        }
    }
}