Skip to content

Instantly share code, notes, and snippets.

@kylesluder
Last active May 15, 2020 06:01
Show Gist options
  • Star 18 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kylesluder/478bf8fd8232bc90eabd to your computer and use it in GitHub Desktop.
Save kylesluder/478bf8fd8232bc90eabd to your computer and use it in GitHub Desktop.
A C#-style Async/Await implementation in Swift
// 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)")
@threeve
Copy link

threeve commented Jun 9, 2014

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.

@JensAyton
Copy link

It’s actually kinda sorta possible in Objective-C. Horrendous, but possible.

https://github.com/nevyn/SPAsync

Mmm, macros.

@al45tair
Copy link

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