InstanceContext.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) Microsoft Corporation. All rights reserved.
  3. //-----------------------------------------------------------------------------
  4. namespace System.ServiceModel
  5. {
  6. using System.Collections.Generic;
  7. using System.Diagnostics;
  8. using System.Runtime;
  9. using System.Runtime.CompilerServices;
  10. using System.ServiceModel.Channels;
  11. using System.ServiceModel.Diagnostics;
  12. using System.ServiceModel.Dispatcher;
  13. using System.Threading;
  14. using System.ServiceModel.Diagnostics.Application;
  15. public sealed class InstanceContext : CommunicationObject, IExtensibleObject<InstanceContext>
  16. {
  17. internal static InstanceContextEmptyCallback NotifyEmptyCallback = new InstanceContextEmptyCallback(InstanceContext.NotifyEmpty);
  18. internal static InstanceContextIdleCallback NotifyIdleCallback = new InstanceContextIdleCallback(InstanceContext.NotifyIdle);
  19. bool autoClose;
  20. InstanceBehavior behavior;
  21. ServiceChannelManager channels;
  22. ConcurrencyInstanceContextFacet concurrency;
  23. ExtensionCollection<InstanceContext> extensions;
  24. readonly ServiceHostBase host;
  25. QuotaThrottle quotaThrottle;
  26. ServiceThrottle serviceThrottle;
  27. int instanceContextManagerIndex;
  28. object serviceInstanceLock = new object();
  29. SynchronizationContext synchronizationContext;
  30. TransactionInstanceContextFacet transaction;
  31. object userObject;
  32. bool wellKnown;
  33. SynchronizedCollection<IChannel> wmiChannels;
  34. bool isUserCreated;
  35. public InstanceContext(object implementation)
  36. : this(null, implementation)
  37. {
  38. }
  39. public InstanceContext(ServiceHostBase host, object implementation)
  40. : this(host, implementation, true)
  41. {
  42. }
  43. internal InstanceContext(ServiceHostBase host, object implementation, bool isUserCreated)
  44. : this(host, implementation, true, isUserCreated)
  45. {
  46. }
  47. internal InstanceContext(ServiceHostBase host, object implementation, bool wellKnown, bool isUserCreated)
  48. {
  49. this.host = host;
  50. if (implementation != null)
  51. {
  52. this.userObject = implementation;
  53. this.wellKnown = wellKnown;
  54. }
  55. this.autoClose = false;
  56. this.channels = new ServiceChannelManager(this);
  57. this.isUserCreated = isUserCreated;
  58. }
  59. public InstanceContext(ServiceHostBase host)
  60. : this(host, true)
  61. {
  62. }
  63. internal InstanceContext(ServiceHostBase host, bool isUserCreated)
  64. {
  65. if (host == null)
  66. {
  67. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("host"));
  68. }
  69. this.host = host;
  70. this.autoClose = true;
  71. this.channels = new ServiceChannelManager(this, NotifyEmptyCallback);
  72. this.isUserCreated = isUserCreated;
  73. }
  74. internal bool IsUserCreated
  75. {
  76. get { return this.isUserCreated; }
  77. set { this.isUserCreated = value; }
  78. }
  79. internal bool IsWellKnown
  80. {
  81. get { return this.wellKnown; }
  82. }
  83. internal bool AutoClose
  84. {
  85. get { return this.autoClose; }
  86. set { this.autoClose = value; }
  87. }
  88. internal InstanceBehavior Behavior
  89. {
  90. get { return this.behavior; }
  91. set
  92. {
  93. if (this.behavior == null)
  94. {
  95. this.behavior = value;
  96. }
  97. }
  98. }
  99. internal ConcurrencyInstanceContextFacet Concurrency
  100. {
  101. get
  102. {
  103. if (this.concurrency == null)
  104. {
  105. lock (this.ThisLock)
  106. {
  107. if (this.concurrency == null)
  108. this.concurrency = new ConcurrencyInstanceContextFacet();
  109. }
  110. }
  111. return this.concurrency;
  112. }
  113. }
  114. internal static InstanceContext Current
  115. {
  116. get { return OperationContext.Current != null ? OperationContext.Current.InstanceContext : null; }
  117. }
  118. protected override TimeSpan DefaultCloseTimeout
  119. {
  120. get
  121. {
  122. if (this.host != null)
  123. {
  124. return this.host.CloseTimeout;
  125. }
  126. else
  127. {
  128. return ServiceDefaults.CloseTimeout;
  129. }
  130. }
  131. }
  132. protected override TimeSpan DefaultOpenTimeout
  133. {
  134. get
  135. {
  136. if (this.host != null)
  137. {
  138. return this.host.OpenTimeout;
  139. }
  140. else
  141. {
  142. return ServiceDefaults.OpenTimeout;
  143. }
  144. }
  145. }
  146. public IExtensionCollection<InstanceContext> Extensions
  147. {
  148. get
  149. {
  150. this.ThrowIfClosed();
  151. lock (this.ThisLock)
  152. {
  153. if (this.extensions == null)
  154. this.extensions = new ExtensionCollection<InstanceContext>(this, this.ThisLock);
  155. return this.extensions;
  156. }
  157. }
  158. }
  159. internal bool HasTransaction
  160. {
  161. get { return (this.transaction != null) && !object.Equals(this.transaction.Attached, null); }
  162. }
  163. public ICollection<IChannel> IncomingChannels
  164. {
  165. get
  166. {
  167. this.ThrowIfClosed();
  168. return channels.IncomingChannels;
  169. }
  170. }
  171. bool IsBusy
  172. {
  173. get
  174. {
  175. if (this.State == CommunicationState.Closed)
  176. return false;
  177. return this.channels.IsBusy;
  178. }
  179. }
  180. bool IsSingleton
  181. {
  182. get
  183. {
  184. return ((this.behavior != null) &&
  185. InstanceContextProviderBase.IsProviderSingleton(this.behavior.InstanceContextProvider));
  186. }
  187. }
  188. public ICollection<IChannel> OutgoingChannels
  189. {
  190. get
  191. {
  192. this.ThrowIfClosed();
  193. return channels.OutgoingChannels;
  194. }
  195. }
  196. public ServiceHostBase Host
  197. {
  198. get
  199. {
  200. this.ThrowIfClosed();
  201. return this.host;
  202. }
  203. }
  204. public int ManualFlowControlLimit
  205. {
  206. get { return this.EnsureQuotaThrottle().Limit; }
  207. set { this.EnsureQuotaThrottle().SetLimit(value); }
  208. }
  209. internal QuotaThrottle QuotaThrottle
  210. {
  211. get { return this.quotaThrottle; }
  212. }
  213. internal ServiceThrottle ServiceThrottle
  214. {
  215. get { return this.serviceThrottle; }
  216. set
  217. {
  218. this.ThrowIfDisposed();
  219. this.serviceThrottle = value;
  220. }
  221. }
  222. internal int InstanceContextManagerIndex
  223. {
  224. get { return this.instanceContextManagerIndex; }
  225. set { this.instanceContextManagerIndex = value; }
  226. }
  227. public SynchronizationContext SynchronizationContext
  228. {
  229. get { return this.synchronizationContext; }
  230. set
  231. {
  232. this.ThrowIfClosedOrOpened();
  233. this.synchronizationContext = value;
  234. }
  235. }
  236. new internal object ThisLock
  237. {
  238. get { return base.ThisLock; }
  239. }
  240. internal TransactionInstanceContextFacet Transaction
  241. {
  242. get
  243. {
  244. if (this.transaction == null)
  245. {
  246. lock (this.ThisLock)
  247. {
  248. if (this.transaction == null)
  249. this.transaction = new TransactionInstanceContextFacet(this);
  250. }
  251. }
  252. return this.transaction;
  253. }
  254. }
  255. internal object UserObject
  256. {
  257. get { return this.userObject; }
  258. }
  259. internal ICollection<IChannel> WmiChannels
  260. {
  261. get
  262. {
  263. if (this.wmiChannels == null)
  264. {
  265. lock (this.ThisLock)
  266. {
  267. if (this.wmiChannels == null)
  268. {
  269. this.wmiChannels = new SynchronizedCollection<IChannel>();
  270. }
  271. }
  272. }
  273. return this.wmiChannels;
  274. }
  275. }
  276. protected override void OnAbort()
  277. {
  278. channels.Abort();
  279. this.Unload();
  280. }
  281. internal IAsyncResult BeginCloseInput(TimeSpan timeout, AsyncCallback callback, object state)
  282. {
  283. return channels.BeginCloseInput(timeout, callback, state);
  284. }
  285. internal void BindRpc(ref MessageRpc rpc)
  286. {
  287. this.ThrowIfClosed();
  288. this.channels.IncrementActivityCount();
  289. rpc.SuccessfullyBoundInstance = true;
  290. }
  291. internal void BindIncomingChannel(ServiceChannel channel)
  292. {
  293. this.ThrowIfDisposed();
  294. channel.InstanceContext = this;
  295. IChannel proxy = (IChannel)channel.Proxy;
  296. this.channels.AddIncomingChannel(proxy);
  297. // CSDMain 265783: Memory Leak on Chat Stress test scenario
  298. // There's a race condition while on one thread we received a new request from underlying sessionful channel
  299. // and on another thread we just aborted the channel. So the channel will be added to the IncomingChannels list of
  300. // ServiceChannelManager and never get a chance to be removed.
  301. if (proxy != null)
  302. {
  303. CommunicationState state = channel.State;
  304. if (state == CommunicationState.Closing
  305. || state == CommunicationState.Closed
  306. || state == CommunicationState.Faulted)
  307. {
  308. this.channels.RemoveChannel(proxy);
  309. }
  310. }
  311. }
  312. void CloseIfNotBusy()
  313. {
  314. if (!(this.State != CommunicationState.Created && this.State != CommunicationState.Opening))
  315. {
  316. Fx.Assert("InstanceContext.CloseIfNotBusy: (this.State != CommunicationState.Created && this.State != CommunicationState.Opening)");
  317. }
  318. if (this.State != CommunicationState.Opened)
  319. return;
  320. if (this.IsBusy)
  321. return;
  322. if (this.behavior.CanUnload(this) == false)
  323. return;
  324. try
  325. {
  326. if (this.State == CommunicationState.Opened)
  327. this.Close();
  328. }
  329. catch (ObjectDisposedException e)
  330. {
  331. DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
  332. }
  333. catch (InvalidOperationException e)
  334. {
  335. DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
  336. }
  337. catch (CommunicationException e)
  338. {
  339. DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
  340. }
  341. catch (TimeoutException e)
  342. {
  343. if (TD.CloseTimeoutIsEnabled())
  344. {
  345. TD.CloseTimeout(e.Message);
  346. }
  347. DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
  348. }
  349. }
  350. internal void CloseInput(TimeSpan timeout)
  351. {
  352. channels.CloseInput(timeout);
  353. }
  354. internal void EndCloseInput(IAsyncResult result)
  355. {
  356. channels.EndCloseInput(result);
  357. }
  358. [MethodImpl(MethodImplOptions.NoInlining)]
  359. internal void CompleteAttachedTransaction()
  360. {
  361. Exception error = null;
  362. if (!this.behavior.TransactionAutoCompleteOnSessionClose)
  363. {
  364. error = new Exception();
  365. if (DiagnosticUtility.ShouldTraceInformation)
  366. TraceUtility.TraceEvent(TraceEventType.Information,
  367. TraceCode.TxCompletionStatusAbortedOnSessionClose,
  368. SR.GetString(SR.TraceCodeTxCompletionStatusAbortedOnSessionClose,
  369. transaction.Attached.TransactionInformation.LocalIdentifier)
  370. );
  371. }
  372. else if (DiagnosticUtility.ShouldTraceInformation)
  373. {
  374. TraceUtility.TraceEvent(TraceEventType.Information,
  375. TraceCode.TxCompletionStatusCompletedForTACOSC,
  376. SR.GetString(SR.TraceCodeTxCompletionStatusCompletedForTACOSC,
  377. transaction.Attached.TransactionInformation.LocalIdentifier)
  378. );
  379. }
  380. transaction.CompletePendingTransaction(transaction.Attached, error);
  381. transaction.Attached = null;
  382. }
  383. QuotaThrottle EnsureQuotaThrottle()
  384. {
  385. lock (this.ThisLock)
  386. {
  387. if (this.quotaThrottle == null)
  388. {
  389. this.quotaThrottle = new QuotaThrottle(ImmutableDispatchRuntime.GotDynamicInstanceContext, this.ThisLock);
  390. this.quotaThrottle.Owner = "InstanceContext";
  391. }
  392. return this.quotaThrottle;
  393. }
  394. }
  395. internal void FaultInternal()
  396. {
  397. this.Fault();
  398. }
  399. public object GetServiceInstance()
  400. {
  401. return this.GetServiceInstance(null);
  402. }
  403. public object GetServiceInstance(Message message)
  404. {
  405. lock (this.serviceInstanceLock)
  406. {
  407. this.ThrowIfClosedOrNotOpen();
  408. object current = this.userObject;
  409. if (current != null)
  410. {
  411. return current;
  412. }
  413. if (this.behavior == null)
  414. {
  415. Exception error = new InvalidOperationException(SR.GetString(SR.SFxInstanceNotInitialized));
  416. if (message != null)
  417. {
  418. throw TraceUtility.ThrowHelperError(error, message);
  419. }
  420. else
  421. {
  422. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(error);
  423. }
  424. }
  425. object newUserObject;
  426. if (message != null)
  427. {
  428. newUserObject = this.behavior.GetInstance(this, message);
  429. }
  430. else
  431. {
  432. newUserObject = this.behavior.GetInstance(this);
  433. }
  434. if (newUserObject != null)
  435. {
  436. this.SetUserObject(newUserObject);
  437. }
  438. return newUserObject;
  439. }
  440. }
  441. public int IncrementManualFlowControlLimit(int incrementBy)
  442. {
  443. return this.EnsureQuotaThrottle().IncrementLimit(incrementBy);
  444. }
  445. void Load()
  446. {
  447. if (this.behavior != null)
  448. {
  449. this.behavior.Initialize(this);
  450. }
  451. if (this.host != null)
  452. {
  453. this.host.BindInstance(this);
  454. }
  455. }
  456. static void NotifyEmpty(InstanceContext instanceContext)
  457. {
  458. if (instanceContext.autoClose)
  459. {
  460. instanceContext.CloseIfNotBusy();
  461. }
  462. }
  463. static void NotifyIdle(InstanceContext instanceContext)
  464. {
  465. instanceContext.CloseIfNotBusy();
  466. }
  467. protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
  468. {
  469. return new CloseAsyncResult(timeout, callback, state, this);
  470. }
  471. protected override void OnEndClose(IAsyncResult result)
  472. {
  473. CloseAsyncResult.End(result);
  474. }
  475. protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
  476. {
  477. return new CompletedAsyncResult(callback, state);
  478. }
  479. protected override void OnEndOpen(IAsyncResult result)
  480. {
  481. CompletedAsyncResult.End(result);
  482. }
  483. protected override void OnClose(TimeSpan timeout)
  484. {
  485. channels.Close(timeout);
  486. this.Unload();
  487. }
  488. protected override void OnClosed()
  489. {
  490. base.OnClosed();
  491. ServiceThrottle throttle = this.serviceThrottle;
  492. if (throttle != null)
  493. {
  494. throttle.DeactivateInstanceContext();
  495. }
  496. }
  497. protected override void OnFaulted()
  498. {
  499. base.OnFaulted();
  500. if (this.IsSingleton && (this.host != null))
  501. {
  502. this.host.FaultInternal();
  503. }
  504. }
  505. protected override void OnOpen(TimeSpan timeout)
  506. {
  507. TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
  508. }
  509. protected override void OnOpened()
  510. {
  511. base.OnOpened();
  512. }
  513. protected override void OnOpening()
  514. {
  515. this.Load();
  516. base.OnOpening();
  517. }
  518. public void ReleaseServiceInstance()
  519. {
  520. this.ThrowIfDisposedOrNotOpen();
  521. this.SetUserObject(null);
  522. }
  523. void SetUserObject(object newUserObject)
  524. {
  525. if (this.behavior != null && !this.wellKnown)
  526. {
  527. object oldUserObject = Interlocked.Exchange(ref this.userObject, newUserObject);
  528. if ((oldUserObject != null) && (this.host != null) && !Object.Equals(oldUserObject, this.host.DisposableInstance))
  529. {
  530. this.behavior.ReleaseInstance(this, oldUserObject);
  531. }
  532. }
  533. }
  534. internal void UnbindRpc(ref MessageRpc rpc)
  535. {
  536. if (rpc.InstanceContext == this && rpc.SuccessfullyBoundInstance)
  537. {
  538. this.channels.DecrementActivityCount();
  539. }
  540. }
  541. internal void UnbindIncomingChannel(ServiceChannel channel)
  542. {
  543. this.channels.RemoveChannel((IChannel)channel.Proxy);
  544. }
  545. void Unload()
  546. {
  547. this.SetUserObject(null);
  548. if (this.host != null)
  549. {
  550. this.host.UnbindInstance(this);
  551. }
  552. }
  553. class CloseAsyncResult : AsyncResult
  554. {
  555. InstanceContext instanceContext;
  556. TimeoutHelper timeoutHelper;
  557. public CloseAsyncResult(TimeSpan timeout, AsyncCallback callback, object state, InstanceContext instanceContext)
  558. : base(callback, state)
  559. {
  560. this.timeoutHelper = new TimeoutHelper(timeout);
  561. this.instanceContext = instanceContext;
  562. IAsyncResult result = this.instanceContext.channels.BeginClose(this.timeoutHelper.RemainingTime(), PrepareAsyncCompletion(new AsyncCompletion(CloseChannelsCallback)), this);
  563. if (result.CompletedSynchronously && CloseChannelsCallback(result))
  564. {
  565. base.Complete(true);
  566. }
  567. }
  568. public static void End(IAsyncResult result)
  569. {
  570. AsyncResult.End<CloseAsyncResult>(result);
  571. }
  572. bool CloseChannelsCallback(IAsyncResult result)
  573. {
  574. Fx.Assert(object.ReferenceEquals(this, result.AsyncState), "AsyncState should be this");
  575. this.instanceContext.channels.EndClose(result);
  576. this.instanceContext.Unload();
  577. return true;
  578. }
  579. }
  580. }
  581. }