@@ -43,7 +43,7 @@ func copyTo_async() async {
43
43
await TL . $other. withValue ( 9999 ) {
44
44
printTaskLocal ( TL . $number) // CHECK: TaskLocal<Int>(defaultValue: 0) (2222)
45
45
printTaskLocal ( TL . $other) // CHECK: TaskLocal<Int>(defaultValue: 0) (9999)
46
- let handle = async {
46
+ let handle = Task {
47
47
printTaskLocal ( TL . $number) // CHECK: TaskLocal<Int>(defaultValue: 0) (2222)
48
48
printTaskLocal ( TL . $other) // CHECK: TaskLocal<Int>(defaultValue: 0) (9999)
49
49
TL . $number. withValue ( 3333 ) {
@@ -52,7 +52,7 @@ func copyTo_async() async {
52
52
}
53
53
}
54
54
55
- _ = await handle. get ( )
55
+ _ = await handle. value
56
56
}
57
57
}
58
58
}
@@ -64,7 +64,7 @@ func copyTo_async_noWait() async {
64
64
TL . $number. withValue ( 1111 ) {
65
65
TL . $number. withValue ( 2222 ) {
66
66
TL . $other. withValue ( 9999 ) {
67
- async {
67
+ Task {
68
68
printTaskLocal ( TL . $number) // CHECK: TaskLocal<Int>(defaultValue: 0) (2222)
69
69
printTaskLocal ( TL . $other) // CHECK: TaskLocal<Int>(defaultValue: 0) (9999)
70
70
TL . $number. withValue ( 3333 ) {
@@ -80,11 +80,51 @@ func copyTo_async_noWait() async {
80
80
await Task . sleep ( 2 * second)
81
81
}
82
82
83
+ @available ( SwiftStdlib 5 . 5 , * )
84
+ class CustomClass {
85
+ @TaskLocal
86
+ static var current : CustomClass ?
87
+
88
+ init ( ) {
89
+ print ( " init \( ObjectIdentifier ( self ) ) " )
90
+ }
91
+
92
+ deinit {
93
+ print ( " deinit \( ObjectIdentifier ( self ) ) " )
94
+ }
95
+ }
96
+
97
+ @available ( SwiftStdlib 5 . 5 , * )
98
+ func test_async_retains( ) async {
99
+ let instance = CustomClass ( )
100
+ CustomClass . $current. withValue ( instance) {
101
+ print ( " BEFORE send: \( String ( reflecting: CustomClass . current) ) " )
102
+ // don't await on the un-structured tasks on purpose, we want to see that the tasks
103
+ // themselves keep the object alive even if we don't hold onto them
104
+ Task {
105
+ print ( " in async task: \( String ( reflecting: CustomClass . current) ) " )
106
+ }
107
+ Task {
108
+ print ( " in async task: \( String ( reflecting: CustomClass . current) ) " )
109
+ }
110
+ print ( " AFTER send: \( String ( reflecting: CustomClass . current) ) " )
111
+ }
112
+
113
+ // CHECK: init
114
+ // CHECK: BEFORE send: Optional(main.CustomClass)
115
+ // CHECK: in async task: Optional(main.CustomClass)
116
+ // CHECK: in async task: Optional(main.CustomClass)
117
+ // the deinit MUST NOT happen before the async tasks runs
118
+ // CHECK: deinit
119
+ await Task . sleep ( 2 * 1_000_000_000 )
120
+ }
121
+
83
122
@available ( SwiftStdlib 5 . 5 , * )
84
123
@main struct Main {
85
124
static func main( ) async {
86
125
await copyTo_async ( )
87
126
await copyTo_async ( )
88
127
await copyTo_async_noWait ( )
128
+ await test_async_retains ( )
89
129
}
90
130
}
0 commit comments