File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 106106
107107** 识别特征** :
108108``` csharp
109- // 曾经尝试过 xxx 方案,但会导致 yyy 问题
110- // var result = DoSomethingWrong() ;
109+ // 曾经尝试过同步等待,但会导致线程池饥饿和死锁
110+ // var result = task.Result ;
111111
112- // 不要使用 xxx,否则会造成 yyy
112+ // 不要使用 SendAsync 的无超时重载,否则会造成连接泄漏
113113// await client.SendAsync(data);
114114
115- // 这里不能用 xxx,因为 yyy
115+ // 这里不能用 Flush,因为底层 SSL 流会抛出 ObjectDisposedException
116116// stream.Flush();
117+
118+ // 不要改成 ConfigureAwait(true),会导致 UI 线程死锁
119+ // await Task.Delay(100).ConfigureAwait(true);
117120```
118121
119122** 处理原则** :
@@ -168,6 +171,25 @@ foreach (var item in list)
168171{
169172 Process (item );
170173}
174+
175+ // ✅ using 语句:优先使用 using declaration(无花括号)
176+ using var stream = File .OpenRead (" file.txt" );
177+ using var reader = new StreamReader (stream );
178+ return reader .ReadToEnd ();
179+
180+ // ✅ using 弃元:仅用于需要资源生命周期但不需要引用的场景
181+ // 例如:分布式锁、性能追踪 Span、临时文件锁等
182+ using var _ = _lock .AcquireLock ();
183+ DoSomething ();
184+ // 方法结束时自动释放锁
185+
186+ // ⚠️ using 语句:仅在需要提前结束作用域时使用花括号
187+ using (var connection = CreateConnection ())
188+ {
189+ connection .Open ();
190+ // ... 执行操作
191+ }
192+ // 这里 connection 已释放,可以继续执行其他操作
171193```
172194
173195### 5.4 Region 组织结构
You can’t perform that action at this time.
0 commit comments