forked from CodeEditApp/CodeEditSourceEditor
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDispatchQueue+dispatchMainIfNot.swift
More file actions
37 lines (33 loc) · 1.16 KB
/
DispatchQueue+dispatchMainIfNot.swift
File metadata and controls
37 lines (33 loc) · 1.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
//
// DispatchQueue+dispatchMainIfNot.swift
// CodeEditSourceEditor
//
// Created by Khan Winter on 9/2/24.
//
import Foundation
/// Helper methods for dispatching (sync or async) on the main queue only if the calling thread is not already the
/// main queue.
extension DispatchQueue {
/// Executes the work item on the main thread, dispatching asynchronously if the thread is not the main thread.
/// - Parameter item: The work item to execute on the main thread.
static func dispatchMainIfNot(_ item: @escaping () -> Void) {
if Thread.isMainThread {
item()
} else {
DispatchQueue.main.async {
item()
}
}
}
/// Executes the work item on the main thread, keeping control on the calling thread until the work item is
/// executed if not already on the main thread.
/// - Parameter item: The work item to execute.
/// - Returns: The value of the work item.
static func waitMainIfNot<T>(_ item: () -> T) -> T {
if Thread.isMainThread {
return item()
} else {
return DispatchQueue.main.asyncAndWait(execute: item)
}
}
}