LocalAppContextSwitches.Common.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Runtime.CompilerServices;
  5. namespace System
  6. {
  7. // Helper method for local caching of compatibility quirks. Keep this lean and simple - this file is included into
  8. // every framework assembly that implements any compatibility quirks.
  9. internal static partial class LocalAppContextSwitches
  10. {
  11. // Returns value of given switch using provided cache.
  12. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  13. internal static bool GetCachedSwitchValue(string switchName, ref int cachedSwitchValue)
  14. {
  15. // The cached switch value has 3 states: 0 - unknown, 1 - true, -1 - false
  16. if (cachedSwitchValue < 0) return false;
  17. if (cachedSwitchValue > 0) return true;
  18. return GetCachedSwitchValueInternal(switchName, ref cachedSwitchValue);
  19. }
  20. private static bool GetCachedSwitchValueInternal(string switchName, ref int cachedSwitchValue)
  21. {
  22. bool isSwitchEnabled;
  23. bool hasSwitch = AppContext.TryGetSwitch(switchName, out isSwitchEnabled);
  24. if (!hasSwitch)
  25. {
  26. isSwitchEnabled = GetSwitchDefaultValue(switchName);
  27. }
  28. AppContext.TryGetSwitch(@"TestSwitch.LocalAppContext.DisableCaching", out bool disableCaching);
  29. if (!disableCaching)
  30. {
  31. cachedSwitchValue = isSwitchEnabled ? 1 /*true*/ : -1 /*false*/;
  32. }
  33. return isSwitchEnabled;
  34. }
  35. // Provides default values for switches if they're not always false by default
  36. private static bool GetSwitchDefaultValue(string switchName)
  37. {
  38. if (switchName == "Switch.System.Runtime.Serialization.SerializationGuard")
  39. {
  40. return true;
  41. }
  42. return false;
  43. }
  44. }
  45. }