Skip to main content

Safe DispatchQueue.main.sync

A safe extension for DispatchQueue.main.sync in Swift, ensuring thread safety when executing tasks on the main thread.

Details

URL: 🔗 Safe DispatchQueue.main.sync (Swift)

Published: Not specified
Last Updated: Not specified

Author: sgr-ksmt

Tags:
Swift, Concurrency, Thread Safety, iOS Development

Platforms Supported: iOS, macOS

Swift Version: 3.0 and above

Key Points​

  • Provides a safe way to execute tasks synchronously on the main thread.
  • Differentiates execution based on whether the current thread is the main thread.
  • Ensures thread safety without blocking the main thread unnecessarily.

Use Cases​

  • Safely updating the UI from background threads.
  • Executing critical code that must run on the main thread without risking deadlock.
  • Simplifying thread management in complex Swift applications.

Alternative Approaches​

  • Using DispatchQueue.main.async for non-blocking calls on the main thread.
  • Implementing thread checks manually before calling DispatchQueue.main.sync.
  • Utilizing third-party libraries for more advanced concurrency management.

Performance Considerations​

  • Minimal overhead when executing on the main thread.
  • Slight delay when switching from a background thread to the main thread, but necessary for safety.
  • Ensures no blocking of the main thread, which maintains app responsiveness.

Code​

extension DispatchQueue {
class func mainSyncSafe(execute work: () -> Void) {
if Thread.isMainThread {
work()
} else {
DispatchQueue.main.sync(execute: work)
}
}

class func mainSyncSafe<T>(execute work: () throws -> T) rethrows -> T {
if Thread.isMainThread {
return try work()
} else {
return try DispatchQueue.main.sync(execute: work)
}
}
}

References​

Read Full Gist→