I’ve learn some articles and have been instructed that if an async operate solely comprises regular synchronous code, then there will not be a suspension throughout runtime, no switching thread,
as this text talked about
If a suspension doesn’t occur, no pause will happen and your operate will proceed to run with the identical effectivity and timings as a synchronous operate.
That final half carries an vital facet impact: utilizing await won’t trigger your code to attend for one runloop to go by earlier than persevering with.
Nevertheless I did a take a look at and it appears would not work that means
struct ContentStructure: View {
var physique: some View {
CustomView()
.process {
print("process begin thread = (Thread.present)")
await fakeExpensiveWork()
print("process finish thread = (Thread.present)")
}
}
}
func fakeExpensiveWork() async {
print("faux costly work thread = (Thread.present)")
}
struct CustomView: View{
init(){
print("init thread = (Thread.present)")
}
var physique: some View{
Listing{
ForEach(1..<100){ _ in
Textual content("Hey, world!")
}
}
}
}
printed:
init thread = <_NSMainThread: 0x600001704000>{quantity = 1, identify = major}
process begin thread = <_NSMainThread: 0x600001704000>{quantity = 1, identify = major}
faux costly work thread = {quantity = 6, identify = (null)}
process finish thread = <_NSMainThread: 0x600001704000>{quantity = 1, identify = major}
Compiled with:
Apple Swift model 5.10 (swiftlang-5.10.0.13 clang-1500.3.9.4)
Goal: arm64-apple-darwin23.6.0
Because the log confirmed, it all the time change a thread to do the fakeExpensiveWork()
even when it simply print a log. After I put Thread.sleep(forTimeInterval: 10)
contained in the fakeExpensiveWork
, the Listing
nonetheless will be scrolled easily.
So is my understanding of this text incorrect, or has Apple up to date the conduct of Swift?