/
ClientBase.cs
1229 lines (1061 loc) · 43.2 KB
/
ClientBase.cs
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
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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.ComponentModel;
using System.Diagnostics;
using System.Runtime;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Diagnostics;
using System.ServiceModel.Dispatcher;
using System.Threading;
using System.Threading.Tasks;
namespace System.ServiceModel
{
public abstract class ClientBase<TChannel> : ICommunicationObject, IDisposable, IAsyncDisposable
where TChannel : class
{
private TChannel _channel;
private ChannelFactoryRef<TChannel> _channelFactoryRef;
private EndpointTrait<TChannel> _endpointTrait;
// Determine whether the proxy can share factory with others. It is false only if the public getters
// are invoked.
private bool _canShareFactory = true;
// Determine whether the proxy is currently holding a cached factory
private bool _useCachedFactory;
// Determine whether we have locked down sharing for this proxy. This is turned on only when the channel
// is created.
private bool _sharingFinalized;
// Determine whether the ChannelFactoryRef has been released. We should release it only once per proxy
private bool _channelFactoryRefReleased;
// Determine whether we have released the last ref count of the ChannelFactory so that we could abort it when it was closing.
private bool _releasedLastRef;
private object finalizeLock = new object();
// Cache at most 32 ChannelFactories
private const int MaxNumChannelFactories = 32;
private static ChannelFactoryRefCache<TChannel> s_factoryRefCache = new ChannelFactoryRefCache<TChannel>(MaxNumChannelFactories);
private static object s_staticLock = new object();
private static object s_cacheLock = new object();
private static CacheSetting s_cacheSetting = CacheSetting.Default;
private static bool s_isCacheSettingReadOnly;
private static AsyncCallback s_onAsyncCallCompleted = Fx.ThunkCallback(new AsyncCallback(OnAsyncCallCompleted));
protected ClientBase()
{
throw new PlatformNotSupportedException(SRP.ConfigurationFilesNotSupported);
}
protected ClientBase(string endpointConfigurationName)
{
throw new PlatformNotSupportedException(SRP.ConfigurationFilesNotSupported);
}
protected ClientBase(string endpointConfigurationName, string remoteAddress)
{
throw new PlatformNotSupportedException(SRP.ConfigurationFilesNotSupported);
}
protected ClientBase(string endpointConfigurationName, EndpointAddress remoteAddress)
{
throw new PlatformNotSupportedException(SRP.ConfigurationFilesNotSupported);
}
protected ClientBase(Binding binding, EndpointAddress remoteAddress)
{
if (binding == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(binding));
}
if (remoteAddress == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(remoteAddress));
}
MakeCacheSettingReadOnly();
if (s_cacheSetting == CacheSetting.AlwaysOn)
{
_endpointTrait = new ProgrammaticEndpointTrait<TChannel>(binding, remoteAddress, null);
InitializeChannelFactoryRef();
}
else
{
_channelFactoryRef = new ChannelFactoryRef<TChannel>(new ChannelFactory<TChannel>(binding, remoteAddress));
_channelFactoryRef.ChannelFactory.TraceOpenAndClose = false;
TryDisableSharing();
}
}
protected ClientBase(ServiceEndpoint endpoint)
{
if (endpoint == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(endpoint));
}
MakeCacheSettingReadOnly();
if (s_cacheSetting == CacheSetting.AlwaysOn)
{
_endpointTrait = new ServiceEndpointTrait<TChannel>(endpoint, null);
InitializeChannelFactoryRef();
}
else
{
_channelFactoryRef = new ChannelFactoryRef<TChannel>(new ChannelFactory<TChannel>(endpoint));
_channelFactoryRef.ChannelFactory.TraceOpenAndClose = false;
TryDisableSharing();
}
}
protected ClientBase(InstanceContext callbackInstance, Binding binding, EndpointAddress remoteAddress)
{
if (callbackInstance == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(callbackInstance));
}
if (binding == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(binding));
}
if (remoteAddress == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(remoteAddress));
}
MakeCacheSettingReadOnly();
if (s_cacheSetting == CacheSetting.AlwaysOn)
{
_endpointTrait = new ProgrammaticEndpointTrait<TChannel>(binding, remoteAddress, callbackInstance);
InitializeChannelFactoryRef();
}
else
{
_channelFactoryRef = new ChannelFactoryRef<TChannel>(
new DuplexChannelFactory<TChannel>(callbackInstance, binding, remoteAddress));
_channelFactoryRef.ChannelFactory.TraceOpenAndClose = false;
TryDisableSharing();
}
}
protected T GetDefaultValueForInitialization<T>()
{
return default(T);
}
private object ThisLock { get; } = new object();
protected TChannel Channel
{
get
{
// created on demand, so that Mort can modify .Endpoint before calling methods on the client
if (_channel == null)
{
lock (ThisLock)
{
if (_channel == null)
{
using (ServiceModelActivity activity = DiagnosticUtility.ShouldUseActivity ? ServiceModelActivity.CreateBoundedActivity() : null)
{
if (DiagnosticUtility.ShouldUseActivity)
{
ServiceModelActivity.Start(activity, SRP.Format(SRP.ActivityOpenClientBase, typeof(TChannel).FullName), ActivityType.OpenClient);
}
if (_useCachedFactory)
{
try
{
CreateChannelInternal();
}
catch (Exception ex)
{
if (_useCachedFactory &&
(ex is CommunicationException ||
ex is ObjectDisposedException ||
ex is TimeoutException))
{
DiagnosticUtility.TraceHandledException(ex, TraceEventType.Warning);
InvalidateCacheAndCreateChannel();
}
else
{
throw;
}
}
}
else
{
CreateChannelInternal();
}
}
}
}
}
return _channel;
}
}
public static CacheSetting CacheSetting
{
get
{
return s_cacheSetting;
}
set
{
lock (s_cacheLock)
{
if (s_isCacheSettingReadOnly && s_cacheSetting != value)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SRP.Format(SRP.SFxImmutableClientBaseCacheSetting, typeof(TChannel).ToString())));
}
else
{
s_cacheSetting = value;
}
}
}
}
public ChannelFactory<TChannel> ChannelFactory
{
get
{
if (s_cacheSetting == CacheSetting.Default)
{
TryDisableSharing();
}
return GetChannelFactory();
}
}
public ClientCredentials ClientCredentials
{
get
{
return ChannelFactory.Credentials;
}
}
public CommunicationState State
{
get
{
IChannel channel = (IChannel)_channel;
if (channel != null)
{
return channel.State;
}
else
{
// we may have failed to create the channel under open, in which case we our factory wouldn't be open
if (!_useCachedFactory)
{
return GetChannelFactory().State;
}
else
{
return CommunicationState.Created;
}
}
}
}
public IClientChannel InnerChannel
{
get
{
return (IClientChannel)Channel;
}
}
public ServiceEndpoint Endpoint
{
get
{
return ChannelFactory.Endpoint;
}
}
public void Open()
{
((ICommunicationObject)this).Open(GetChannelFactory().InternalOpenTimeout);
}
public Task OpenAsync()
{
return OpenAsync(GetChannelFactory().InternalOpenTimeout);
}
private async Task OpenAsync(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
await TaskHelpers.EnsureDefaultTaskScheduler();
if (!_useCachedFactory)
{
await GetChannelFactory().OpenHelperAsync(timeoutHelper.RemainingTime());
}
await InnerChannel.OpenHelperAsync(timeoutHelper.RemainingTime());
}
public void Abort()
{
IChannel channel = (IChannel)_channel;
if (channel != null)
{
channel.Abort();
}
if (!_channelFactoryRefReleased)
{
lock (s_staticLock)
{
if (!_channelFactoryRefReleased)
{
if (_channelFactoryRef.Release())
{
_releasedLastRef = true;
}
_channelFactoryRefReleased = true;
}
}
}
// Abort the ChannelFactory if we released the last one. We should be able to abort it when another thread is closing it.
if (_releasedLastRef)
{
_channelFactoryRef.Abort();
}
}
public void Close()
{
((ICommunicationObject)this).Close(GetChannelFactory().InternalCloseTimeout);
}
public Task CloseAsync()
{
var timeout = GetChannelFactory().InternalCloseTimeout;
return CloseAsync(timeout);
}
private async Task CloseAsync(TimeSpan timeout)
{
using (ServiceModelActivity activity = DiagnosticUtility.ShouldUseActivity ? ServiceModelActivity.CreateBoundedActivity() : null)
{
if (DiagnosticUtility.ShouldUseActivity)
{
ServiceModelActivity.Start(activity, SRP.Format(SRP.ActivityCloseClientBase, typeof(TChannel).FullName), ActivityType.Close);
}
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
await TaskHelpers.EnsureDefaultTaskScheduler();
if (_channel != null)
{
await InnerChannel.CloseHelperAsync(timeoutHelper.RemainingTime());
}
if (!_channelFactoryRefReleased)
{
lock (s_staticLock)
{
if (!_channelFactoryRefReleased)
{
if (_channelFactoryRef.Release())
{
_releasedLastRef = true;
}
_channelFactoryRefReleased = true;
}
}
// Close the factory outside of the lock so that we can abort from a different thread.
if (_releasedLastRef)
{
if (_useCachedFactory)
{
_channelFactoryRef.Abort();
}
else
{
await GetChannelFactory().CloseHelperAsync(timeoutHelper.RemainingTime());
}
}
}
}
}
// This ensures that the cachesetting (on, off or default) cannot be modified by
// another ClientBase instance of matching TChannel after the first instance is created.
private void MakeCacheSettingReadOnly()
{
if (s_isCacheSettingReadOnly)
{
return;
}
lock (s_cacheLock)
{
s_isCacheSettingReadOnly = true;
}
}
void CreateChannelInternal()
{
try
{
_channel = CreateChannel();
if (_sharingFinalized)
{
if (_canShareFactory && !_useCachedFactory)
{
// It is OK to add ChannelFactory to the cache now.
TryAddChannelFactoryToCache();
}
}
}
finally
{
if (!_sharingFinalized && s_cacheSetting == CacheSetting.Default)
{
// this.CreateChannel() is not called. For safety, we disable sharing.
TryDisableSharing();
}
}
}
protected virtual TChannel CreateChannel()
{
if (_sharingFinalized)
{
return GetChannelFactory().CreateChannel();
}
lock (finalizeLock)
{
_sharingFinalized = true;
return GetChannelFactory().CreateChannel();
}
}
void IDisposable.Dispose()
{
Close();
}
async ValueTask IAsyncDisposable.DisposeAsync()
{
try
{
// Only want to call Close if it is in the Opened state
if (State == CommunicationState.Opened)
{
await CloseAsync();
}
// Anything not closed by this point should be aborted
if (State != CommunicationState.Closed)
{
Abort();
}
}
catch (CommunicationException)
{
Abort();
}
catch (TimeoutException)
{
Abort();
}
}
void ICommunicationObject.Open(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
if (!_useCachedFactory)
{
GetChannelFactory().Open(timeoutHelper.RemainingTime());
}
InnerChannel.Open(timeoutHelper.RemainingTime());
}
void ICommunicationObject.Close(TimeSpan timeout)
{
using (ServiceModelActivity activity = DiagnosticUtility.ShouldUseActivity ? ServiceModelActivity.CreateBoundedActivity() : null)
{
if (DiagnosticUtility.ShouldUseActivity)
{
ServiceModelActivity.Start(activity, SRP.Format(SRP.ActivityCloseClientBase, typeof(TChannel).FullName), ActivityType.Close);
}
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
if (_channel != null)
{
InnerChannel.Close(timeoutHelper.RemainingTime());
}
if (!_channelFactoryRefReleased)
{
lock (s_staticLock)
{
if (!_channelFactoryRefReleased)
{
if (_channelFactoryRef.Release())
{
_releasedLastRef = true;
}
_channelFactoryRefReleased = true;
}
}
// Close the factory outside of the lock so that we can abort from a different thread.
if (_releasedLastRef)
{
if (_useCachedFactory)
{
_channelFactoryRef.Abort();
}
else
{
_channelFactoryRef.Close(timeoutHelper.RemainingTime());
}
}
}
}
}
event EventHandler ICommunicationObject.Closed
{
add
{
InnerChannel.Closed += value;
}
remove
{
InnerChannel.Closed -= value;
}
}
event EventHandler ICommunicationObject.Closing
{
add
{
InnerChannel.Closing += value;
}
remove
{
InnerChannel.Closing -= value;
}
}
event EventHandler ICommunicationObject.Faulted
{
add
{
InnerChannel.Faulted += value;
}
remove
{
InnerChannel.Faulted -= value;
}
}
event EventHandler ICommunicationObject.Opened
{
add
{
InnerChannel.Opened += value;
}
remove
{
InnerChannel.Opened -= value;
}
}
event EventHandler ICommunicationObject.Opening
{
add
{
InnerChannel.Opening += value;
}
remove
{
InnerChannel.Opening -= value;
}
}
IAsyncResult ICommunicationObject.BeginClose(AsyncCallback callback, object state)
{
return ((ICommunicationObject)this).BeginClose(GetChannelFactory().InternalCloseTimeout, callback, state);
}
IAsyncResult ICommunicationObject.BeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
return CloseAsync(timeout).ToApm(callback, state);
}
void ICommunicationObject.EndClose(IAsyncResult result)
{
result.ToApmEnd();
}
IAsyncResult ICommunicationObject.BeginOpen(AsyncCallback callback, object state)
{
return ((ICommunicationObject)this).BeginOpen(GetChannelFactory().InternalOpenTimeout, callback, state);
}
IAsyncResult ICommunicationObject.BeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
return OpenAsync(timeout).ToApm(callback, state);
}
void ICommunicationObject.EndOpen(IAsyncResult result)
{
result.ToApmEnd();
}
ChannelFactory<TChannel> GetChannelFactory()
{
return _channelFactoryRef.ChannelFactory;
}
void InitializeChannelFactoryRef()
{
Fx.Assert(_channelFactoryRef == null, "The channelFactory should have never been assigned");
Fx.Assert(_canShareFactory, "GetChannelFactoryFromCache can be called only when canShareFactory is true");
lock (s_staticLock)
{
ChannelFactoryRef<TChannel> factoryRef;
if (s_factoryRefCache.TryGetValue(_endpointTrait, out factoryRef))
{
if (factoryRef.ChannelFactory.State != CommunicationState.Opened)
{
// Remove the bad ChannelFactory.
s_factoryRefCache.Remove(_endpointTrait);
}
else
{
_channelFactoryRef = factoryRef;
_channelFactoryRef.AddRef();
_useCachedFactory = true;
if (WcfEventSource.Instance.ClientBaseChannelFactoryCacheHitIsEnabled())
{
WcfEventSource.Instance.ClientBaseChannelFactoryCacheHit(this);
}
return;
}
}
}
if (_channelFactoryRef == null)
{
// Creating the ChannelFactory at initial time to catch configuration exception earlier.
_channelFactoryRef = CreateChannelFactoryRef(_endpointTrait);
}
}
static ChannelFactoryRef<TChannel> CreateChannelFactoryRef(EndpointTrait<TChannel> endpointTrait)
{
Fx.Assert(endpointTrait != null, "The endpointTrait should not be null when the factory can be shared.");
ChannelFactory<TChannel> channelFactory = endpointTrait.CreateChannelFactory();
channelFactory.TraceOpenAndClose = false;
return new ChannelFactoryRef<TChannel>(channelFactory);
}
// Once the channel is created, we can't disable caching.
// This method can be called safely multiple times.
// this.sharingFinalized is set the first time the method is called.
// Subsequent calls are essentially no-ops.
void TryDisableSharing()
{
if (_sharingFinalized)
{
return;
}
lock (finalizeLock)
{
if (_sharingFinalized)
{
return;
}
_canShareFactory = false;
_sharingFinalized = true;
if (_useCachedFactory)
{
ChannelFactoryRef<TChannel> pendingFactoryRef = _channelFactoryRef;
_channelFactoryRef = CreateChannelFactoryRef(_endpointTrait);
_useCachedFactory = false;
lock (s_staticLock)
{
if (!pendingFactoryRef.Release())
{
pendingFactoryRef = null;
}
}
if (pendingFactoryRef != null)
{
pendingFactoryRef.Abort();
}
}
}
// can be done outside the lock since the lines below do not access shared data.
// also the use of this.sharingFinalized in the lines above ensures that tracing
// happens only once and only when needed.
if (WcfEventSource.Instance.ClientBaseUsingLocalChannelFactoryIsEnabled())
{
WcfEventSource.Instance.ClientBaseUsingLocalChannelFactory(this);
}
}
void TryAddChannelFactoryToCache()
{
Fx.Assert(_canShareFactory, "This should be called only when this proxy can share ChannelFactory.");
Fx.Assert(_channelFactoryRef.ChannelFactory.State == CommunicationState.Opened,
"The ChannelFactory must be in Opened state for caching.");
// Lock the cache and add the item to synchronize with lookup.
lock (s_staticLock)
{
ChannelFactoryRef<TChannel> cfRef;
if (!s_factoryRefCache.TryGetValue(_endpointTrait, out cfRef))
{
// Increment the ref count before adding to the cache.
_channelFactoryRef.AddRef();
s_factoryRefCache.Add(_endpointTrait, _channelFactoryRef);
_useCachedFactory = true;
if (WcfEventSource.Instance.ClientBaseCachedChannelFactoryCountIsEnabled())
{
WcfEventSource.Instance.ClientBaseCachedChannelFactoryCount(s_factoryRefCache.Count, MaxNumChannelFactories, this);
}
}
}
}
// NOTE: This should be called inside ThisLock
void InvalidateCacheAndCreateChannel()
{
RemoveFactoryFromCache();
TryDisableSharing();
CreateChannelInternal();
}
void RemoveFactoryFromCache()
{
lock (s_staticLock)
{
ChannelFactoryRef<TChannel> factoryRef;
if (s_factoryRefCache.TryGetValue(_endpointTrait, out factoryRef))
{
if (object.ReferenceEquals(_channelFactoryRef, factoryRef))
{
s_factoryRefCache.Remove(_endpointTrait);
}
}
}
}
// WARNING: changes in the signature/name of the following delegates must be applied to the
// ClientClassGenerator.cs as well, otherwise the ClientClassGenerator would generate wrong code.
protected delegate IAsyncResult BeginOperationDelegate(object[] inValues, AsyncCallback asyncCallback, object state);
protected delegate object[] EndOperationDelegate(IAsyncResult result);
// WARNING: Any changes in the signature/name of the following type and its ctor must be applied to the
// ClientClassGenerator.cs as well, otherwise the ClientClassGenerator would generate wrong code.
protected class InvokeAsyncCompletedEventArgs : AsyncCompletedEventArgs
{
internal InvokeAsyncCompletedEventArgs(object[] results, Exception error, bool cancelled, object userState)
: base(error, cancelled, userState)
{
Results = results;
}
public object[] Results { get; }
}
// WARNING: Any changes in the signature/name of the following method ctor must be applied to the
// ClientClassGenerator.cs as well, otherwise the ClientClassGenerator would generate wrong code.
protected void InvokeAsync(BeginOperationDelegate beginOperationDelegate, object[] inValues,
EndOperationDelegate endOperationDelegate, SendOrPostCallback operationCompletedCallback, object userState)
{
if (beginOperationDelegate == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(beginOperationDelegate));
}
if (endOperationDelegate == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(endOperationDelegate));
}
AsyncOperation asyncOperation = AsyncOperationManager.CreateOperation(userState);
AsyncOperationContext context = new AsyncOperationContext(asyncOperation, endOperationDelegate, operationCompletedCallback);
Exception error = null;
object[] results = null;
IAsyncResult result = null;
try
{
result = beginOperationDelegate(inValues, s_onAsyncCallCompleted, context);
if (result.CompletedSynchronously)
{
results = endOperationDelegate(result);
}
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
error = e;
}
if (error != null || result.CompletedSynchronously) /* result cannot be null if error == null */
{
CompleteAsyncCall(context, results, error);
}
}
private static void OnAsyncCallCompleted(IAsyncResult result)
{
if (result.CompletedSynchronously)
{
return;
}
AsyncOperationContext context = (AsyncOperationContext)result.AsyncState;
Exception error = null;
object[] results = null;
try
{
results = context.EndDelegate(result);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
error = e;
}
CompleteAsyncCall(context, results, error);
}
private static void CompleteAsyncCall(AsyncOperationContext context, object[] results, Exception error)
{
if (context.CompletionCallback != null)
{
InvokeAsyncCompletedEventArgs e = new InvokeAsyncCompletedEventArgs(results, error, false, context.AsyncOperation.UserSuppliedState);
context.AsyncOperation.PostOperationCompleted(context.CompletionCallback, e);
}
else
{
context.AsyncOperation.OperationCompleted();
}
}
protected class AsyncOperationContext
{
private SendOrPostCallback _completionCallback;
internal AsyncOperationContext(AsyncOperation asyncOperation, EndOperationDelegate endDelegate, SendOrPostCallback completionCallback)
{
AsyncOperation = asyncOperation;
EndDelegate = endDelegate;
_completionCallback = completionCallback;
}
internal AsyncOperation AsyncOperation { get; }
internal EndOperationDelegate EndDelegate { get; }
internal SendOrPostCallback CompletionCallback
{
get
{
return _completionCallback;
}
}
}
protected class ChannelBase<T> : IClientChannel, IOutputChannel, IRequestChannel, IChannelBaseProxy
where T : class
{
private ServiceChannel _channel;
private ImmutableClientRuntime _runtime;
protected ChannelBase(ClientBase<T> client)
{
if (client.Endpoint.Address == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SRP.SFxChannelFactoryEndpointAddressUri));
}
ChannelFactory<T> cf = client.ChannelFactory;
cf.EnsureOpened(); // to prevent the NullReferenceException that is thrown if the ChannelFactory is not open when cf.ServiceChannelFactory is accessed.
_channel = cf.ServiceChannelFactory.CreateServiceChannel(client.Endpoint.Address, client.Endpoint.Address.Uri);
_channel.InstanceContext = cf.CallbackInstance;
_runtime = _channel.ClientRuntime.GetRuntime();
}
protected IAsyncResult BeginInvoke(string methodName, object[] args, AsyncCallback callback, object state)
{
object[] inArgs = new object[args.Length + 2];
Array.Copy(args, inArgs, args.Length);
inArgs[inArgs.Length - 2] = callback;
inArgs[inArgs.Length - 1] = state;
MethodCall methodCall = new MethodCall(inArgs);
ProxyOperationRuntime op = GetOperationByName(methodName);
object[] ins = op.MapAsyncBeginInputs(methodCall, out callback, out state);
return _channel.BeginCall(op.Action, op.IsOneWay, op, ins, callback, state);
}
protected object EndInvoke(string methodName, object[] args, IAsyncResult result)
{
object[] inArgs = new object[args.Length + 1];
Array.Copy(args, inArgs, args.Length);
inArgs[inArgs.Length - 1] = result;
MethodCall methodCall = new MethodCall(inArgs);
ProxyOperationRuntime op = GetOperationByName(methodName);
object[] outs;
op.MapAsyncEndInputs(methodCall, out result, out outs);
object ret = _channel.EndCall(op.Action, outs, result);
object[] retArgs = op.MapAsyncOutputs(methodCall, outs, ref ret);
if (retArgs != null)
{
Fx.Assert(retArgs.Length == inArgs.Length, "retArgs.Length should be equal to inArgs.Length");
Array.Copy(retArgs, args, args.Length);
}
return ret;
}
private ProxyOperationRuntime GetOperationByName(string methodName)
{
ProxyOperationRuntime op = _runtime.GetOperationByName(methodName);
if (op == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SRP.Format(SRP.SFxMethodNotSupported1, methodName)));
}
return op;
}
bool IClientChannel.AllowInitializationUI
{
get { return ((IClientChannel)_channel).AllowInitializationUI; }
set { ((IClientChannel)_channel).AllowInitializationUI = value; }
}
bool IClientChannel.DidInteractiveInitialization
{
get { return ((IClientChannel)_channel).DidInteractiveInitialization; }
}
Uri IClientChannel.Via
{
get { return ((IClientChannel)_channel).Via; }
}
event EventHandler<UnknownMessageReceivedEventArgs> IClientChannel.UnknownMessageReceived
{
add { ((IClientChannel)_channel).UnknownMessageReceived += value; }
remove { ((IClientChannel)_channel).UnknownMessageReceived -= value; }
}
void IClientChannel.DisplayInitializationUI()
{
((IClientChannel)_channel).DisplayInitializationUI();
}