DispatchQueue+Extension.swift 868 B

123456789101112131415161718192021222324252627282930313233
  1. //
  2. // DispatchQueue+Extension.swift
  3. // O2Platform
  4. //
  5. // Created by FancyLou on 2019/10/23.
  6. // Copyright © 2019 zoneland. All rights reserved.
  7. //
  8. import Foundation
  9. extension DispatchQueue {
  10. private static var _onceTracker = [String]()
  11. /**
  12. Executes a block of code, associated with a unique token, only once. The code is thread safe and will
  13. only execute the code once even in the presence of multithreaded calls.
  14. - parameter token: A unique reverse DNS style name such as com.vectorform.<name> or a GUID
  15. - parameter block: Block to execute once
  16. */
  17. class func once(token: String, block:()->Void) {
  18. objc_sync_enter(self); defer { objc_sync_exit(self) }
  19. if _onceTracker.contains(token) {
  20. return
  21. }
  22. _onceTracker.append(token)
  23. block()
  24. }
  25. }