Skip to content

Commit 474b5d4

Browse files
authored
Merge pull request #2543 from Frizlab/operation_fix
Fix Running Synchronous Operations Without a Queue
2 parents 6bd47ad + 8561356 commit 474b5d4

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

Foundation/Operation.swift

+1-1
Original file line numberDiff line numberDiff line change
@@ -347,7 +347,7 @@ open class Operation : NSObject {
347347
_state = .executing
348348
Operation.observeValue(forKeyPath: _NSOperationIsExecuting, ofObject: self)
349349

350-
_queue?._execute(self)
350+
_queue?._execute(self) ?? main()
351351
}
352352

353353
if __NSOperationState.executing == _state {

TestFoundation/TestOperationQueue.swift

+24
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ class TestOperationQueue : XCTestCase {
1515
("test_OperationPriorities", test_OperationPriorities),
1616
("test_OperationCount", test_OperationCount),
1717
("test_AsyncOperation", test_AsyncOperation),
18+
("test_SyncOperationWithoutAQueue", test_SyncOperationWithoutAQueue),
1819
("test_isExecutingWorks", test_isExecutingWorks),
1920
("test_MainQueueGetter", test_MainQueueGetter),
2021
("test_CancelOneOperation", test_CancelOneOperation),
@@ -105,6 +106,18 @@ class TestOperationQueue : XCTestCase {
105106
XCTAssertTrue(operation.isFinished)
106107
}
107108

109+
func test_SyncOperationWithoutAQueue() {
110+
let operation = SyncOperation()
111+
XCTAssertFalse(operation.isExecuting)
112+
XCTAssertFalse(operation.isFinished)
113+
114+
operation.start()
115+
116+
XCTAssertFalse(operation.isExecuting)
117+
XCTAssertTrue(operation.isFinished)
118+
XCTAssertTrue(operation.hasRun)
119+
}
120+
108121
func test_MainQueueGetter() {
109122
XCTAssertTrue(OperationQueue.main === OperationQueue.main)
110123

@@ -345,3 +358,14 @@ class AsyncOperation: Operation {
345358
}
346359

347360
}
361+
362+
class SyncOperation: Operation {
363+
364+
var hasRun = false
365+
366+
override func main() {
367+
Thread.sleep(forTimeInterval: 1)
368+
hasRun = true
369+
}
370+
371+
}

0 commit comments

Comments
 (0)