Skip to content

Commit ef7729e

Browse files
committed
Introduce small performance gains
Leverage a boolean flag instead of && Start the background thread to avoid deadlocking
1 parent 533ad1c commit ef7729e

1 file changed

Lines changed: 12 additions & 3 deletions

File tree

src/libraries/System.Private.CoreLib/src/System/DateTimeOffset.Android.cs

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ public readonly partial struct DateTimeOffset
1010
private static bool s_androidTZDataLoaded;
1111
private static readonly object s_localUtcOffsetLock = new();
1212
private static Thread? s_loadAndroidTZData;
13+
private static bool s_startNewBackgroundThread = true;
1314

1415
// Now on Android does the following
1516
// 1) quickly returning a fast path result when first called if the right AppContext data element is set
@@ -31,7 +32,7 @@ public static DateTimeOffset Now
3132
if (s_androidTZDataLoaded) // The background thread finished, the cache is loaded.
3233
return ToLocalTime(utcDateTime, true);
3334

34-
if (!s_androidTZDataLoaded && s_loadAndroidTZData == null) // The cache isn't loaded and no background thread has been created
35+
if (s_startNewBackgroundThread) // The cache isn't loaded and no background thread has been created
3536
{
3637
lock (s_localUtcOffsetLock)
3738
{
@@ -43,21 +44,29 @@ public static DateTimeOffset Now
4344
if (s_loadAndroidTZData == null)
4445
{
4546
s_loadAndroidTZData = new Thread(() => {
47+
// We only want to start one background thread
48+
s_startNewBackgroundThread = false;
49+
4650
// Delay the background thread to avoid impacting startup, if it still coincides after 1s, startup is already perceived as slow
4751
Thread.Sleep(1000);
52+
4853
_ = TimeZoneInfo.Local; // Load AndroidTZData
54+
s_androidTZDataLoaded = true;
55+
4956
lock (s_localUtcOffsetLock)
5057
{
51-
s_androidTZDataLoaded = true;
5258
s_loadAndroidTZData = null; // Ensure thread is cleared when cache is loaded
5359
}
5460
});
5561
s_loadAndroidTZData.IsBackground = true;
56-
s_loadAndroidTZData.Start();
5762
}
5863
}
64+
65+
if (s_startNewBackgroundThread)
66+
s_loadAndroidTZData.Start();
5967
}
6068

69+
6170
object? localDateTimeOffset = AppContext.GetData("System.TimeZoneInfo.LocalDateTimeOffset");
6271
if (localDateTimeOffset == null) // If no offset property provided through monovm app context, default
6372
return ToLocalTime(utcDateTime, true);

0 commit comments

Comments
 (0)