vds_ios/VDS/Extensions/DispatchQueue+Once.swift
Matt Bruce 20895847ed added fonts
Signed-off-by: Matt Bruce <matt.bruce@verizon.com>
2022-07-27 18:26:26 -05:00

43 lines
1.1 KiB
Swift

//
// DispatchQueue+Once.swift
// VDS
//
// Created by Matt Bruce on 7/27/22.
//
import Foundation
extension DispatchQueue {
private static var _onceTracker = [String]()
public class func once(
file: String = #file,
function: String = #function,
line: Int = #line,
block: () -> Void
) {
let token = "\(file):\(function):\(line)"
once(token: token, block: block)
}
/**
Executes a block of code, associated with a unique token, only once. The code is thread safe and will
only execute the code once even in the presence of multithreaded calls.
- parameter token: A unique reverse DNS style name such as com.vectorform.<name> or a GUID
- parameter block: Block to execute once
*/
public class func once(
token: String,
block: () -> Void
) {
objc_sync_enter(self)
defer { objc_sync_exit(self) }
guard !_onceTracker.contains(token) else { return }
_onceTracker.append(token)
block()
}
}