Skip to content

Commit 8a5531c

Browse files
committed
fix(time): 修复线程安全和异常处理问题
- 为 _currentTimeZone 字段添加 volatile 关键字确保多线程可见性 - SetTimeZone(string) 方法改为返回 bool,允许调用者检测配置错误
1 parent f99526a commit 8a5531c

1 file changed

Lines changed: 14 additions & 3 deletions

File tree

GameFrameX.Foundation.Utility/Time/TimerHelper.cs

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,11 @@ public static partial class TimerHelper
3939
/// <summary>
4040
/// 当前时区,默认为 UTC
4141
/// </summary>
42-
private static TimeZoneInfo _currentTimeZone = TimeZoneInfo.Utc;
42+
/// <remarks>
43+
/// 使用 volatile 关键字确保多线程环境下的可见性。
44+
/// 对于更复杂的线程安全需求,建议使用锁或其他同步机制。
45+
/// </remarks>
46+
private static volatile TimeZoneInfo _currentTimeZone = TimeZoneInfo.Utc;
4347

4448
/// <summary>
4549
/// 获取当前时区
@@ -62,15 +66,22 @@ public static void SetTimeZone(TimeZoneInfo timeZone)
6266
/// 设置当前时区
6367
/// </summary>
6468
/// <param name="timeZoneId">时区ID,如 "China Standard Time" 或 "UTC"</param>
65-
public static void SetTimeZone(string timeZoneId)
69+
/// <returns>如果成功设置时区返回 <c>true</c>;如果时区ID无效则返回 <c>false</c> 并回退到 UTC</returns>
70+
/// <remarks>
71+
/// 当传入无效的时区ID时,方法会回退到 UTC 时区并返回 <c>false</c>。
72+
/// 这允许调用者检测配置错误并采取适当的措施。
73+
/// </remarks>
74+
public static bool SetTimeZone(string timeZoneId)
6675
{
6776
try
6877
{
6978
_currentTimeZone = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId);
79+
return true;
7080
}
71-
catch
81+
catch (Exception)
7282
{
7383
_currentTimeZone = TimeZoneInfo.Utc;
84+
return false;
7485
}
7586
}
7687

0 commit comments

Comments
 (0)