File: InstanceContext.cs

package info (click to toggle)
mono 4.6.2.7%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 778,148 kB
  • ctags: 914,052
  • sloc: cs: 5,779,509; xml: 2,773,713; ansic: 432,645; sh: 14,749; makefile: 12,361; perl: 2,488; python: 1,434; cpp: 849; asm: 531; sql: 95; sed: 16; php: 1
file content (672 lines) | stat: -rw-r--r-- 20,903 bytes parent folder | download | duplicates (9)
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
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
//-----------------------------------------------------------------------------

namespace System.ServiceModel
{
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Runtime;
    using System.Runtime.CompilerServices;
    using System.ServiceModel.Channels;
    using System.ServiceModel.Diagnostics;
    using System.ServiceModel.Dispatcher;
    using System.Threading;
    using System.ServiceModel.Diagnostics.Application;

    public sealed class InstanceContext : CommunicationObject, IExtensibleObject<InstanceContext>
    {
        internal static InstanceContextEmptyCallback NotifyEmptyCallback = new InstanceContextEmptyCallback(InstanceContext.NotifyEmpty);
        internal static InstanceContextIdleCallback NotifyIdleCallback = new InstanceContextIdleCallback(InstanceContext.NotifyIdle);

        bool autoClose;
        InstanceBehavior behavior;
        ServiceChannelManager channels;
        ConcurrencyInstanceContextFacet concurrency;
        ExtensionCollection<InstanceContext> extensions;
        readonly ServiceHostBase host;
        QuotaThrottle quotaThrottle;
        ServiceThrottle serviceThrottle;
        int instanceContextManagerIndex;
        object serviceInstanceLock = new object();
        SynchronizationContext synchronizationContext;
        TransactionInstanceContextFacet transaction;
        object userObject;
        bool wellKnown;
        SynchronizedCollection<IChannel> wmiChannels;
        bool isUserCreated;

        public InstanceContext(object implementation)
            : this(null, implementation)
        {
        }

        public InstanceContext(ServiceHostBase host, object implementation)
            : this(host, implementation, true)
        {
        }

        internal InstanceContext(ServiceHostBase host, object implementation, bool isUserCreated)
            : this(host, implementation, true, isUserCreated)
        {
        }

        internal InstanceContext(ServiceHostBase host, object implementation, bool wellKnown, bool isUserCreated)
        {
            this.host = host;
            if (implementation != null)
            {
                this.userObject = implementation;
                this.wellKnown = wellKnown;
            }
            this.autoClose = false;
            this.channels = new ServiceChannelManager(this);
            this.isUserCreated = isUserCreated;
        }

        public InstanceContext(ServiceHostBase host)
            : this(host, true)
        {
        }

        internal InstanceContext(ServiceHostBase host, bool isUserCreated)
        {
            if (host == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("host"));
            }

            this.host = host;
            this.autoClose = true;
            this.channels = new ServiceChannelManager(this, NotifyEmptyCallback);
            this.isUserCreated = isUserCreated;
        }

        internal bool IsUserCreated
        {
            get { return this.isUserCreated; }
            set { this.isUserCreated = value; }
        }

        internal bool IsWellKnown
        {
            get { return this.wellKnown; }
        }

        internal bool AutoClose
        {
            get { return this.autoClose; }
            set { this.autoClose = value; }
        }

        internal InstanceBehavior Behavior
        {
            get { return this.behavior; }
            set
            {
                if (this.behavior == null)
                {
                    this.behavior = value;
                }
            }
        }

        internal ConcurrencyInstanceContextFacet Concurrency
        {
            get
            {
                if (this.concurrency == null)
                {
                    lock (this.ThisLock)
                    {
                        if (this.concurrency == null)
                            this.concurrency = new ConcurrencyInstanceContextFacet();
                    }
                }

                return this.concurrency;
            }
        }

        internal static InstanceContext Current
        {
            get { return OperationContext.Current != null ? OperationContext.Current.InstanceContext : null; }
        }

        protected override TimeSpan DefaultCloseTimeout
        {
            get
            {
                if (this.host != null)
                {
                    return this.host.CloseTimeout;
                }
                else
                {
                    return ServiceDefaults.CloseTimeout;
                }
            }
        }

        protected override TimeSpan DefaultOpenTimeout
        {
            get
            {
                if (this.host != null)
                {
                    return this.host.OpenTimeout;
                }
                else
                {
                    return ServiceDefaults.OpenTimeout;
                }
            }
        }

        public IExtensionCollection<InstanceContext> Extensions
        {
            get
            {
                this.ThrowIfClosed();
                lock (this.ThisLock)
                {
                    if (this.extensions == null)
                        this.extensions = new ExtensionCollection<InstanceContext>(this, this.ThisLock);
                    return this.extensions;
                }
            }
        }

        internal bool HasTransaction
        {
            get { return (this.transaction != null) && !object.Equals(this.transaction.Attached, null); }
        }

        public ICollection<IChannel> IncomingChannels
        {
            get
            {
                this.ThrowIfClosed();
                return channels.IncomingChannels;
            }
        }

        bool IsBusy
        {
            get
            {
                if (this.State == CommunicationState.Closed)
                    return false;
                return this.channels.IsBusy;
            }
        }

        bool IsSingleton
        {
            get
            {
                return ((this.behavior != null) &&
                        InstanceContextProviderBase.IsProviderSingleton(this.behavior.InstanceContextProvider));
            }
        }

        public ICollection<IChannel> OutgoingChannels
        {
            get
            {
                this.ThrowIfClosed();
                return channels.OutgoingChannels;
            }
        }

        public ServiceHostBase Host
        {
            get
            {
                this.ThrowIfClosed();
                return this.host;
            }
        }

        public int ManualFlowControlLimit
        {
            get { return this.EnsureQuotaThrottle().Limit; }
            set { this.EnsureQuotaThrottle().SetLimit(value); }
        }

        internal QuotaThrottle QuotaThrottle
        {
            get { return this.quotaThrottle; }
        }

        internal ServiceThrottle ServiceThrottle
        {
            get { return this.serviceThrottle; }
            set
            {
                this.ThrowIfDisposed();
                this.serviceThrottle = value;
            }
        }

        internal int InstanceContextManagerIndex
        {
            get { return this.instanceContextManagerIndex; }
            set { this.instanceContextManagerIndex = value; }
        }

        public SynchronizationContext SynchronizationContext
        {
            get { return this.synchronizationContext; }
            set
            {
                this.ThrowIfClosedOrOpened();
                this.synchronizationContext = value;
            }
        }

        new internal object ThisLock
        {
            get { return base.ThisLock; }
        }

        internal TransactionInstanceContextFacet Transaction
        {
            get
            {
                if (this.transaction == null)
                {
                    lock (this.ThisLock)
                    {
                        if (this.transaction == null)
                            this.transaction = new TransactionInstanceContextFacet(this);
                    }
                }

                return this.transaction;
            }
        }

        internal object UserObject
        {
            get { return this.userObject; }
        }

        internal ICollection<IChannel> WmiChannels
        {
            get
            {
                if (this.wmiChannels == null)
                {
                    lock (this.ThisLock)
                    {
                        if (this.wmiChannels == null)
                        {
                            this.wmiChannels = new SynchronizedCollection<IChannel>();
                        }
                    }
                }
                return this.wmiChannels;
            }
        }

        protected override void OnAbort()
        {
            channels.Abort();
            this.Unload();
        }

        internal IAsyncResult BeginCloseInput(TimeSpan timeout, AsyncCallback callback, object state)
        {
            return channels.BeginCloseInput(timeout, callback, state);
        }

        internal void BindRpc(ref MessageRpc rpc)
        {
            this.ThrowIfClosed();
            this.channels.IncrementActivityCount();
            rpc.SuccessfullyBoundInstance = true;
        }

        internal void BindIncomingChannel(ServiceChannel channel)
        {
            this.ThrowIfDisposed();

            channel.InstanceContext = this;
            IChannel proxy = (IChannel)channel.Proxy;
            this.channels.AddIncomingChannel(proxy);

            // CSDMain 265783: Memory Leak on Chat Stress test scenario
            // There's a race condition while on one thread we received a new request from underlying sessionful channel
            // and on another thread we just aborted the channel. So the channel will be added to the IncomingChannels list of 
            // ServiceChannelManager and never get a chance to be removed.
            if (proxy != null)
            {
                CommunicationState state = channel.State;
                if (state == CommunicationState.Closing
                    || state == CommunicationState.Closed
                    || state == CommunicationState.Faulted)
                {
                    this.channels.RemoveChannel(proxy);
                }
            }
        }


        void CloseIfNotBusy()
        {
            if (!(this.State != CommunicationState.Created && this.State != CommunicationState.Opening))
            {
                Fx.Assert("InstanceContext.CloseIfNotBusy: (this.State != CommunicationState.Created && this.State != CommunicationState.Opening)");
            }

            if (this.State != CommunicationState.Opened)
                return;

            if (this.IsBusy)
                return;

            if (this.behavior.CanUnload(this) == false)
                return;

            try
            {
                if (this.State == CommunicationState.Opened)
                    this.Close();
            }
            catch (ObjectDisposedException e)
            {
                DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
            }
            catch (InvalidOperationException e)
            {
                DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
            }
            catch (CommunicationException e)
            {
                DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
            }
            catch (TimeoutException e)
            {
                if (TD.CloseTimeoutIsEnabled())
                {
                    TD.CloseTimeout(e.Message);
                }
                DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
            }
        }

        internal void CloseInput(TimeSpan timeout)
        {
            channels.CloseInput(timeout);
        }

        internal void EndCloseInput(IAsyncResult result)
        {
            channels.EndCloseInput(result);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        internal void CompleteAttachedTransaction()
        {
            Exception error = null;

            if (!this.behavior.TransactionAutoCompleteOnSessionClose)
            {
                error = new Exception();
                if (DiagnosticUtility.ShouldTraceInformation)
                    TraceUtility.TraceEvent(TraceEventType.Information,
                                                                    TraceCode.TxCompletionStatusAbortedOnSessionClose,
                                                                    SR.GetString(SR.TraceCodeTxCompletionStatusAbortedOnSessionClose,
                                                                                    transaction.Attached.TransactionInformation.LocalIdentifier)
                                                                    );

            }
            else if (DiagnosticUtility.ShouldTraceInformation)
            {
                TraceUtility.TraceEvent(TraceEventType.Information,
                                                                TraceCode.TxCompletionStatusCompletedForTACOSC,
                                                                SR.GetString(SR.TraceCodeTxCompletionStatusCompletedForTACOSC,
                                                                                transaction.Attached.TransactionInformation.LocalIdentifier)
                                                                );
            }

            transaction.CompletePendingTransaction(transaction.Attached, error);
            transaction.Attached = null;
        }

        QuotaThrottle EnsureQuotaThrottle()
        {
            lock (this.ThisLock)
            {
                if (this.quotaThrottle == null)
                {
                    this.quotaThrottle = new QuotaThrottle(ImmutableDispatchRuntime.GotDynamicInstanceContext, this.ThisLock);
                    this.quotaThrottle.Owner = "InstanceContext";
                }
                return this.quotaThrottle;
            }
        }

        internal void FaultInternal()
        {
            this.Fault();
        }

        public object GetServiceInstance()
        {
            return this.GetServiceInstance(null);
        }

        public object GetServiceInstance(Message message)
        {
            lock (this.serviceInstanceLock)
            {
                this.ThrowIfClosedOrNotOpen();

                object current = this.userObject;

                if (current != null)
                {
                    return current;
                }

                if (this.behavior == null)
                {
                    Exception error = new InvalidOperationException(SR.GetString(SR.SFxInstanceNotInitialized));
                    if (message != null)
                    {
                        throw TraceUtility.ThrowHelperError(error, message);
                    }
                    else
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(error);
                    }
                }

                object newUserObject;
                if (message != null)
                {
                    newUserObject = this.behavior.GetInstance(this, message);
                }
                else
                {
                    newUserObject = this.behavior.GetInstance(this);
                }
                if (newUserObject != null)
                {
                    this.SetUserObject(newUserObject);
                }

                return newUserObject;
            }
        }

        public int IncrementManualFlowControlLimit(int incrementBy)
        {
            return this.EnsureQuotaThrottle().IncrementLimit(incrementBy);
        }

        void Load()
        {
            if (this.behavior != null)
            {
                this.behavior.Initialize(this);
            }

            if (this.host != null)
            {
                this.host.BindInstance(this);
            }
        }

        static void NotifyEmpty(InstanceContext instanceContext)
        {
            if (instanceContext.autoClose)
            {
                instanceContext.CloseIfNotBusy();
            }
        }

        static void NotifyIdle(InstanceContext instanceContext)
        {
            instanceContext.CloseIfNotBusy();
        }

        protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
        {
            return new CloseAsyncResult(timeout, callback, state, this);
        }

        protected override void OnEndClose(IAsyncResult result)
        {
            CloseAsyncResult.End(result);
        }

        protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
        {
            return new CompletedAsyncResult(callback, state);
        }

        protected override void OnEndOpen(IAsyncResult result)
        {
            CompletedAsyncResult.End(result);
        }

        protected override void OnClose(TimeSpan timeout)
        {
            channels.Close(timeout);
            this.Unload();
        }

        protected override void OnClosed()
        {
            base.OnClosed();

            ServiceThrottle throttle = this.serviceThrottle;
            if (throttle != null)
            {
                throttle.DeactivateInstanceContext();
            }
        }

        protected override void OnFaulted()
        {
            base.OnFaulted();

            if (this.IsSingleton && (this.host != null))
            {
                this.host.FaultInternal();
            }
        }

        protected override void OnOpen(TimeSpan timeout)
        {
            TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
        }

        protected override void OnOpened()
        {
            base.OnOpened();
        }

        protected override void OnOpening()
        {
            this.Load();
            base.OnOpening();
        }

        public void ReleaseServiceInstance()
        {
            this.ThrowIfDisposedOrNotOpen();
            this.SetUserObject(null);
        }

        void SetUserObject(object newUserObject)
        {
            if (this.behavior != null && !this.wellKnown)
            {
                object oldUserObject = Interlocked.Exchange(ref this.userObject, newUserObject);

                if ((oldUserObject != null) && (this.host != null) && !Object.Equals(oldUserObject, this.host.DisposableInstance))
                {
                    this.behavior.ReleaseInstance(this, oldUserObject);
                }
            }
        }

        internal void UnbindRpc(ref MessageRpc rpc)
        {
            if (rpc.InstanceContext == this && rpc.SuccessfullyBoundInstance)
            {
                this.channels.DecrementActivityCount();
            }
        }

        internal void UnbindIncomingChannel(ServiceChannel channel)
        {
            this.channels.RemoveChannel((IChannel)channel.Proxy);
        }

        void Unload()
        {
            this.SetUserObject(null);

            if (this.host != null)
            {
                this.host.UnbindInstance(this);
            }
        }

        class CloseAsyncResult : AsyncResult
        {
            InstanceContext instanceContext;
            TimeoutHelper timeoutHelper;

            public CloseAsyncResult(TimeSpan timeout, AsyncCallback callback, object state, InstanceContext instanceContext)
                : base(callback, state)
            {
                this.timeoutHelper = new TimeoutHelper(timeout);
                this.instanceContext = instanceContext;
                IAsyncResult result = this.instanceContext.channels.BeginClose(this.timeoutHelper.RemainingTime(), PrepareAsyncCompletion(new AsyncCompletion(CloseChannelsCallback)), this);
                if (result.CompletedSynchronously && CloseChannelsCallback(result))
                {
                    base.Complete(true);
                }
            }

            public static void End(IAsyncResult result)
            {
                AsyncResult.End<CloseAsyncResult>(result);
            }

            bool CloseChannelsCallback(IAsyncResult result)
            {
                Fx.Assert(object.ReferenceEquals(this, result.AsyncState), "AsyncState should be this");
                this.instanceContext.channels.EndClose(result);
                this.instanceContext.Unload();
                return true;
            }
        }
    }
}