LocalAppContextSwitches.Common.cs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839
  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;
  5. using System.Runtime.CompilerServices;
  6. namespace System
  7. {
  8. // Helper method for local caching of compatibility quirks. Keep this lean and simple - this file is included into
  9. // every framework assembly that implements any compatibility quirks.
  10. internal static partial class LocalAppContextSwitches
  11. {
  12. // Returns value of given switch using provided cache.
  13. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  14. internal static bool GetCachedSwitchValue(string switchName, ref int cachedSwitchValue)
  15. {
  16. // The cached switch value has 3 states: 0 - unknown, 1 - true, -1 - false
  17. if (cachedSwitchValue < 0) return false;
  18. if (cachedSwitchValue > 0) return true;
  19. return GetCachedSwitchValueInternal(switchName, ref cachedSwitchValue);
  20. }
  21. private static bool GetCachedSwitchValueInternal(string switchName, ref int cachedSwitchValue)
  22. {
  23. bool isSwitchEnabled;
  24. AppContext.TryGetSwitch(switchName, out isSwitchEnabled);
  25. AppContext.TryGetSwitch(@"TestSwitch.LocalAppContext.DisableCaching", out bool disableCaching);
  26. if (!disableCaching)
  27. {
  28. cachedSwitchValue = isSwitchEnabled ? 1 /*true*/ : -1 /*false*/;
  29. }
  30. return isSwitchEnabled;
  31. }
  32. }
  33. }