DispatchWorkItem not notifying main thread - swift

Note: This is not duplicate question I have already seen Dispatch group - cannot notify to main thread
There is nothing answered about DispatchWorkItem
I have code like below
let dwi3 = DispatchWorkItem {
print("start DispatchWorkItem \(Thread.isMainThread)")
sleep(2)
print("end DispatchWorkItem")
}
let myDq = DispatchQueue(label: "A custom dispatch queue")
dwi3.notify(queue: myDq) {
print("notify")
}
DispatchQueue.global().async(execute: dwi3)
Which is working correctly (I can see notify on console) and not in main thread start DispatchWorkItem false
start DispatchWorkItem false
end DispatchWorkItem
notify
Now I am trying to notify to main thread using
dwi3.notify(queue: DispatchQueue.main) {
print("notify")
}
But it never calls , I have read and found that if Thread is blocked then situation occurs. but i am already executing DisptachWorkItem in DispatchQueue.global()
Please Anyone can help me on this that what actually going on ?

If you are running asynchronous code in a playground then you need to enable indefinite execution, otherwise execution may end before the callbacks execute.
Add the following lines to your code in the playground:
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
Once you do this, you will see that the notify executes correctly on the main queue.

Related

In XCTest: how to test that a function forced execution onto main thread

In the UI class I have a method that accesses UI elements, and hence is supposed to force itself onto a main thread. Here's a minimal example of what I mean:
class SomeUI {
func doWorkOnUI() {
guard Thread.isMainThread else {
DispatchQueue.main.async {
self.doWorkOnUI()
}
return
}
print("Doing the work on UI and running on main thread")
}
}
In the tests, of course there's no problem to test the case when doWorkOnUI() is already running on main thread. I just do this:
func testWhenOnMainThread() {
let testedObject = SomeUI()
let expectation = XCTestExpectation(description: "Completed doWorkOnUI")
DispatchQueue.main.async {
testedObject.doWorkOnUI()
expectation.fulfill()
}
wait(for: [expectation], timeout: 10.0)
// Proceed to some validation
}
That is: force execution onto main thread. Wait for it to complete. Do some checks.
But how to test the opposite case, i.e. ensure that function forced itself to run on main thread when called from the background thread?
For example if I do something like:
...
DispatchQueue.global(qos: .background).async {
testedObject.doWorkOnUI()
expectation.fulfill()
}
...
I just tested that function got executed from the background thread. But I didn't explicitly check that it ran on main thread. Of course, since this function accesses UI elements, the expectation is that it crashes if not forced on main thread. So is "no crash" the only testable condition here? Is there anything better?
When there is an outer closure in the background and an inner closure on the main thread, we want two tests:
Call the outer closure. Do a wait for expectations. Wait for 0.01 seconds. Check that the expected work was performed.
Call the outer closure. This time, don't wait for expectations. Check that the work was not performed.
To use this pattern, I think you'll have to change your code so that the tests can call the outer closure directly without having to do an async dance already. This suggests that your design is too deep to be testable without some changes.
Find a way for an intermediate object to capture the closure. That is, instead of directly calling DispatchQueue.global(qos: .background).async, make a type that represents this action. Then a Test Spy version can capture the closure instead of dispatching it to the background, so that your tests can invoke it directly. Then you can test the call back to main thread using async wait.

Can I use a DispatchSemaphore to control a thread on main queue?

Apparently I can only use DispatchSemaphore if I deal with different queues. But what if I want to run async code on the same queue (in this case the main queue).
let s = DispatchSemaphore(value : 0)
DispatchQueue.main.async {
s.signal()
}
s.wait()
This snippet doesn't work, because the async code is also waiting, because the semaphore blocked the main queue.
Can I do this with semaphore? Or do I need to run the async code on a different queue?
ps. I know I could use sync, instead of async and semaphore in this snippet. But This is just an example code to reproduce an async call.
All of this in on the main thread, so the semaphore.signal() will never be called because the thread will stop on the semaphore.wait() and not continue on.
If you are trying to run some async code and have the main thread wait for it, run that code on a different queue and have it signal the semaphore when it's done, allowing the main thread to continue.
what if I want to run async code on the same queue (in this case the main queue).
Then use DispatchGroup instead. That is not what DispatchSemaphore is for.
Run this code in a playground.
import Foundation
let d = DispatchGroup()
var v:Int = 1
d.enter()
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
v = 7
d.leave()
}
d.notify(queue: DispatchQueue.main) {
print("v = \(v)")
}
The output will be v = 7. If you comment out d.enter() and d.leave() then the output will be v = 1.
If I call async, don't I run that code on a different thread?
No, you need to understand thread run loops in general and iOS's Main Event Loop specifically.

Swift 4. Wait for async result of HealthKit HKQuery before continuing execution

Problem is how to wait for an async query on HealthKit to return a result BEFORE allowing execution to move on. The returned data is critical for further execution.
I know this has been asked/solved many times and I have read many of the posts, however I have tried completion handlers, Dispatch sync and Dispatch Groups and have not been able to come up with an implementation that works.
Using completion handler
per Wait for completion handler to finish - Swift
This calls a method to run a HealthKit Query:
func readHK() {
var block: Bool = false
hk.findLastBloodGlucoseInHealthKit(completion: { (result) -> Void in
block = true
if !(result) {
print("Problem with HK data")
}
else {
print ("Got HK data OK")
}
})
while !(block) {
}
// now move on to the next thing ...
}
This does work. Using "block" variable to hold execution pending the callback in concept seems not that different from blocking semaphores, but it's really ugly and asking for trouble if the completion doesn't return for whatever reason. Is there a better way?
Using Dispatch Groups
If I put Dispatch Group at the calling function level:
Calling function:
func readHK() {
var block: Bool = false
dispatchGroup.enter()
hk.findLastBloodGlucoseInHealthKit(dg: dispatchGroup)
print ("Back from readHK")
dispatchGroup.notify(queue: .main) {
print("Function complete")
block = true
}
while !(block){
}
}
Receiving function:
func findLastBloodGlucoseInHealthKit(dg: DispatchGroup) {
print ("Read last HK glucose")
let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false)
let query = HKSampleQuery(sampleType: glucoseQuantity!, predicate: nil, limit: 10, sortDescriptors: [sortDescriptor]) { (query, results, error) in
// .... other stuff
dg.leave()
The completion executes OK, but the .notify method is never called, so the block variable is never updated, program hangs and never exits from the while statement.
Put Dispatch Group in target function but leave .notify at calling level:
func readHK() {
var done: Bool = false
hk.findLastBloodGlucoseInHealthKit()
print ("Back from readHK")
hk.dispatchGroup.notify(queue: .main) {
print("done function")
done = true
}
while !(done) {
}
}
Same issue.
Using Dispatch
Documentation and other S.O posts say: “If you want to wait for the block to complete use the sync() method instead.”
But what does “complete” mean? It seems that it does not mean complete the function AND get the later async completion. For example, the below does not hold execution until the completion returns:
func readHK() {
DispatchQueue.global(qos: .background).sync {
hk.findLastBloodGlucoseInHealthKit()
}
print ("Back from readHK")
}
Thank you for any help.
Yes, please don't fight the async nature of things. You will almost always lose, either by making an inefficient app (timers and other delays) or by creating opportunities for hard-to-diagnose bugs by implementing your own blocking functions.
I am far from a Swift/iOS expert, but it appears that your best alternatives are to use Grand Central Dispatch, or one of the third-party libraries for managing async work. Look at PromiseKit, for example, although I haven't seen as nice a Swift Promises/Futures library as JavaScript's bluebird.
You can use DispatchGroup to keep track of the completion handler for queries. Call the "enter" method when you set up the query, and the "leave" at the end of the results handler, not after the query has been set up or executed. Make sure that you exit even if the query is completed with an error. I am not sure why you are having trouble because this works fine in my app. The trick, I think, is to make sure you always "leave()" the dispatch group no matter what goes wrong.
If you prefer, you can set a barrier task in the DispatchQueue -- this will only execute when all of the earlier tasks in the queue have completed -- instead of using a DispatchGroup. You do this by adding the correct options to the DispatchWorkItem.

GCD swift 4 thread safety

I have a function which control some resources, for example:
var resource: Int?
func changeSomeResources() {
resource = 1
// rewriting keychain parameters
// working with UIApplication.shared
}
Then I add this function to global thread several times
DispatchQueue.global(qos: .userInitiated).async {
changeSomeResources()
}
DispatchQueue.global(qos: .userInitiated).async {
changeSomeResources()
}
Can I get some thread problems in this case except race condition ?
For example if both functions will try to change a resource at the same time
The global dispatch queues are concurrent, so that does not protect
your function from being called simultaneously from multiple threads.
If you want to serialize access to the resources then you have to
create a serial queue:
let myQueue = DispatchQueue(label: "myQueue", qos: .userInitiated)
Then all work items dispatched to this queue are executed sequentially:
myQueue.async {
changeSomeResources()
}
Note also that UIApplication – as a UI related resource – must only
be accessed on the main thread:
DispatchQueue.main.async {
// working with UIApplication.shared
}
Xcode also has options “Thread Sanitizer” and “Main Thread Checker”
(in the “Diagnostics” pane of the scheme settings) which can help
to detect threading problems.

Why my NSOperation is not cancelling?

I have this code to add a NSOperation instance to a queue
let operation = NSBlockOperation()
operation.addExecutionBlock({
self.asyncMethod() { (result, error) in
if operation.cancelled {
return
}
// etc
}
})
operationQueue.addOperation(operation)
When user leaves the view that triggered this above code I cancel operation doing
operationQueue.cancelAllOperations()
When testing cancelation, I'm 100% sure cancel is executing before async method returns so I expect operation.cancelled to be true. Unfortunately this is not happening and I'm not able to realize why
I'm executing cancellation on viewWillDisappear
EDIT
asyncMethod contains a network operation that runs in a different thread. That's why the callback is there: to handle network operation returns. The network operation is performed deep into the class hierarchy but I want to handle NSOperations at root level.
Calling the cancel method of this object sets the value of this
property to YES. Once canceled, an operation must move to the finished
state.
Canceling an operation does not actively stop the receiver’s code from
executing. An operation object is responsible for calling this method
periodically and stopping itself if the method returns YES.
You should always check the value of this property before doing any
work towards accomplishing the operation’s task, which typically means
checking it at the beginning of your custom main method. It is
possible for an operation to be cancelled before it begins executing
or at any time while it is executing. Therefore, checking the value at
the beginning of your main method (and periodically throughout that
method) lets you exit as quickly as possible when an operation is
cancelled.
import Foundation
let operation1 = NSBlockOperation()
let operation2 = NSBlockOperation()
let queue = NSOperationQueue()
operation1.addExecutionBlock { () -> Void in
repeat {
usleep(10000)
print(".", terminator: "")
} while !operation1.cancelled
}
operation2.addExecutionBlock { () -> Void in
repeat {
usleep(15000)
print("-", terminator: "")
} while !operation2.cancelled
}
queue.addOperation(operation1)
queue.addOperation(operation2)
sleep(1)
queue.cancelAllOperations()
try this simple example in playground.
if it is really important to run another asynchronous code, try this
operation.addExecutionBlock({
if operation.cancelled {
return
}
self.asyncMethod() { (result, error) in
// etc
}
})
it's because you doing work wrong. You cancel operation after it executed.
Check this code, block executed in one background thread. Before execution start – operation cancel, remove first block from queue.
Swift 4
let operationQueue = OperationQueue()
operationQueue.qualityOfService = .background
let ob1 = BlockOperation {
print("ExecutionBlock 1. Executed!")
}
let ob2 = BlockOperation {
print("ExecutionBlock 2. Executed!")
}
operationQueue.addOperation(ob1)
operationQueue.addOperation(ob2)
ob1.cancel()
// ExecutionBlock 2. Executed!
Swift 2
let operationQueue = NSOperationQueue()
operationQueue.qualityOfService = .Background
let ob1 = NSBlockOperation()
ob1.addExecutionBlock {
print("ExecutionBlock 1. Executed!")
}
let ob2 = NSBlockOperation()
ob2.addExecutionBlock {
print("ExecutionBlock 2. Executed!")
}
operationQueue.addOperation(ob1)
operationQueue.addOperation(ob2)
ob1.cancel()
// ExecutionBlock 2. Executed!
The Operation does not wait for your asyncMethod to be finished. Therefore, it immediately returns if you add it to the Queue. And this is because you wrap your async network operation in an async NSOperation.
NSOperation is designed to give a more advanced async handling instead for just calling performSelectorInBackground. This means that NSOperation is used to bring complex and long running operations in background and not block the main thread. A good article of a typically used NSOperation can be found here:
http://www.raywenderlich.com/19788/how-to-use-nsoperations-and-nsoperationqueues
For your particular use case, it does not make sense to use an NSOperation here, instead you should just cancel your running network request.
It does not make sense to put an asynchronous function into a block with NSBlockOperation. What you probably want is a proper subclass of NSOperation as a concurrent operation which executes an asynchronous work load. Subclassing an NSOperation correctly is however not that easy as it should.
You may take a look here reusable subclass for NSOperation for an example implementation.
I am not 100% sure what you are looking for, but maybe what you need is to pass the operation, as parameter, into the asyncMethod() and test for cancelled state in there?
operation.addExecutionBlock({
asyncMethod(operation) { (result, error) in
// Result code
}
})
operationQueue.addOperation(operation)
func asyncMethod(operation: NSBlockOperation, fun: ((Any, Any)->Void)) {
// Do stuff...
if operation.cancelled {
// Do something...
return // <- Or whatever makes senes
}
}