Created
September 11, 2014 16:35
-
-
Save chriseidhof/18e41721a0be7924c99b to your computer and use it in GitHub Desktop.
nilResultAfterTimeOut
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
id nilResultAfterTimeOut(int64_t timeoutInNanoSeconds, ResultBlock block) { | |
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0); | |
dispatch_time_t timeoutTime = dispatch_time(DISPATCH_TIME_NOW, timeoutInNanoSeconds); | |
__block id result = nil; | |
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); | |
dispatch_async(queue, ^{ | |
result = block(); | |
dispatch_semaphore_signal(semaphore); | |
}); | |
dispatch_semaphore_wait(semaphore, timeoutTime); | |
return result; | |
} | |
// Examples | |
id result = nilResultAfterTimeOut(1 * NSEC_PER_SEC, ^id{ | |
sleep(2); | |
return @5; | |
}); // returns nil | |
id result = nilResultAfterTimeOut(3 * NSEC_PER_SEC, ^id{ | |
sleep(2); | |
return @5; | |
}); // returns @5 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment