State.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. namespace CommonLang
  6. {
  7. public class State<T>
  8. {
  9. private T mValue;
  10. public T Value { get { return mValue; } }
  11. public State(T value)
  12. {
  13. this.mValue = value;
  14. }
  15. public bool ChangeState(T value)
  16. {
  17. if (!mValue.Equals(value))
  18. {
  19. mValue = value;
  20. return true;
  21. }
  22. return false;
  23. }
  24. public bool CompareChangeState(T expect, T new_value)
  25. {
  26. if (expect.Equals(mValue))
  27. {
  28. mValue = new_value;
  29. return true;
  30. }
  31. return false;
  32. }
  33. }
  34. public class AtomicState<T>
  35. {
  36. private T mValue;
  37. public T Value { get { lock (this) { return mValue; } } }
  38. public AtomicState(T value)
  39. {
  40. this.mValue = value;
  41. }
  42. public bool ChangeState(T value)
  43. {
  44. lock (this)
  45. {
  46. if (!mValue.Equals(value))
  47. {
  48. mValue = value;
  49. return true;
  50. }
  51. return false;
  52. }
  53. }
  54. public bool CompareChangeState(T expect, T new_value)
  55. {
  56. lock (this)
  57. {
  58. if (expect.Equals(mValue))
  59. {
  60. mValue = new_value;
  61. return true;
  62. }
  63. return false;
  64. }
  65. }
  66. }
  67. }