From 4c5637203b8e427fb91fefcd233af1ae803a7ba1 Mon Sep 17 00:00:00 2001 From: Nick Bourdakos Date: Mon, 11 Aug 2025 18:26:34 -0700 Subject: [PATCH] Dispatch FireNow to a background queue to avoid blocking UI PiperOrigin-RevId: 793875585 --- .../platform/implementation/apple/timer.mm | 37 ++++++++++--------- 1 file changed, 20 insertions(+), 17 deletions(-) diff --git a/internal/platform/implementation/apple/timer.mm b/internal/platform/implementation/apple/timer.mm index 86e68c7f..67dd4c3d 100644 --- a/internal/platform/implementation/apple/timer.mm +++ b/internal/platform/implementation/apple/timer.mm @@ -107,26 +107,29 @@ bool Timer::Stop() { } bool Timer::FireNow() { - absl::AnyInvocable callback_to_run; - { - absl::MutexLock lock(&mutex_); + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) { + absl::AnyInvocable callback_to_run; + { + absl::MutexLock lock(&mutex_); - // Don't fire if there's no callback or if a callback is already in progress. - if (!callback_ || callback_running_) { - return false; + // Don't fire if there's no callback or if a callback is already in progress. + if (!callback_ || callback_running_) { + return; + } + callback_running_ = true; + callback_to_run = std::move(callback_); } - callback_running_ = true; - callback_to_run = std::move(callback_); - } - // Execute callback outside of the lock. - callback_to_run(); - { - absl::MutexLock lock(&mutex_); - callback_ = std::move(callback_to_run); - callback_running_ = false; - condvar_.Signal(); // Notify Stop() if it's waiting. - } + // Execute callback outside of the lock. + callback_to_run(); + { + absl::MutexLock lock(&mutex_); + callback_ = std::move(callback_to_run); + callback_running_ = false; + condvar_.Signal(); // Notify Stop() if it's waiting. + } + }); + return true; }