OperationContextScope.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) Microsoft Corporation. All rights reserved.
  3. //-----------------------------------------------------------------------------
  4. namespace System.ServiceModel
  5. {
  6. using System;
  7. using System.ServiceModel.Channels;
  8. using System.Threading;
  9. public sealed class OperationContextScope : IDisposable
  10. {
  11. [ThreadStatic]
  12. static OperationContextScope currentScope;
  13. OperationContext currentContext;
  14. bool disposed;
  15. readonly OperationContext originalContext = OperationContext.Current;
  16. readonly OperationContextScope originalScope = OperationContextScope.currentScope;
  17. readonly Thread thread = Thread.CurrentThread;
  18. public OperationContextScope(IContextChannel channel)
  19. {
  20. this.PushContext(new OperationContext(channel));
  21. }
  22. public OperationContextScope(OperationContext context)
  23. {
  24. this.PushContext(context);
  25. }
  26. public void Dispose()
  27. {
  28. if (!this.disposed)
  29. {
  30. this.disposed = true;
  31. this.PopContext();
  32. }
  33. }
  34. void PushContext(OperationContext context)
  35. {
  36. this.currentContext = context;
  37. OperationContextScope.currentScope = this;
  38. OperationContext.Current = this.currentContext;
  39. }
  40. void PopContext()
  41. {
  42. if (this.thread != Thread.CurrentThread)
  43. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxInvalidContextScopeThread0)));
  44. if (OperationContextScope.currentScope != this)
  45. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxInterleavedContextScopes0)));
  46. if (OperationContext.Current != this.currentContext)
  47. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxContextModifiedInsideScope0)));
  48. OperationContextScope.currentScope = this.originalScope;
  49. OperationContext.Current = this.originalContext;
  50. if (this.currentContext != null)
  51. this.currentContext.SetClientReply(null, false);
  52. }
  53. }
  54. }