Last active
May 15, 2020 06:01
-
-
Save kylesluder/478bf8fd8232bc90eabd to your computer and use it in GitHub Desktop.
A C#-style Async/Await implementation in Swift
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
// A much better version of C#-style Async/Await. It can return values! | |
import Cocoa | |
struct Await<T> { | |
// private | |
let group: dispatch_group_t | |
let getResult: () -> T | |
// public | |
func await() -> T { return getResult() } | |
} | |
func async<T>(queue: dispatch_queue_t, block: () -> T) -> Await<T> { | |
let group = dispatch_group_create() | |
var result: T? | |
dispatch_group_async(group, queue) { result = block() } | |
return Await(group: group, getResult: { dispatch_group_wait(group, DISPATCH_TIME_FOREVER); return result! }) | |
} | |
let q = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) | |
let t = async(q) { () -> Int in return 2 } | |
let v = t.await() | |
println("Value is \(v)") |
It’s actually kinda sorta possible in Objective-C. Horrendous, but possible.
https://github.com/nevyn/SPAsync
Mmm, macros.
I quite like the terse nature of this implementation, but it does, as threeve said, suffer from the problem that await
blocks. It’s probably worth anyone reading this taking a look at my blog post and the related Async framework, since that results in pretty much the exact behaviour that C# programmers are after, give or take (i.e. non-blocking await
).
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is basically the
Task<T>
bit of async/await, but the truly useful part of await in C# is that it transforms your code into a continuation, so that when you await an async task you aren't still blocking the thread. It essentially allows you to write synchronous-looking code that is still asynchronous. It's not really possible to get that without language/compiler support though.