news 2026/6/10 20:59:41

yield break 与 yield return null 的区别详解

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
yield break 与 yield return null 的区别详解

核心区别概述

特性yield return nullyield break
主要作用暂停协程,等待下一帧继续立即终止协程执行
执行流程协程暂停,稍后恢复协程完全结束,不再执行
返回值返回 null(等待一帧)结束迭代器,不返回值
后续代码协程内后续代码会在下一帧执行协程内后续代码永远不会执行

详细解释与示例

1.yield return null- 暂停并继续

csharp

IEnumerator ExampleYieldNull() { Debug.Log("第1步 - 开始"); // 暂停一帧 yield return null; Debug.Log("第2步 - 一帧后执行"); // 这行会执行 // 再暂停一帧 yield return null; Debug.Log("第3步 - 再一帧后执行"); // 这行也会执行 } // 输出结果: // 第1步 - 开始 // (等待一帧) // 第2步 - 一帧后执行 // (等待一帧) // 第3步 - 再一帧后执行

2.yield break- 立即终止

csharp

IEnumerator ExampleYieldBreak() { Debug.Log("第1步 - 开始"); // 立即终止协程 yield break; Debug.Log("第2步 - 这行永远不会执行"); // ❌ 不会执行 yield return null; Debug.Log("第3步 - 这行也不会执行"); // ❌ 不会执行 } // 输出结果: // 第1步 - 开始 // (协程立即结束,没有后续输出)

实际应用场景对比

场景1:条件性提前退出

csharp

IEnumerator LoadDataWithTimeout(float timeout) { float startTime = Time.time; while (!IsDataLoaded()) { // 检查超时 if (Time.time - startTime > timeout) { Debug.Log("加载超时,提前退出"); yield break; // 立即终止协程 } // 等待一帧后继续检查 yield return null; } Debug.Log("数据加载完成"); // 如果超时,这行不会执行 }

场景2:循环中的区别

csharp

// 使用 yield return null IEnumerator LoopWithYieldNull() { for (int i = 0; i < 5; i++) { if (i == 2) { yield return null; // 只是暂停一帧,循环继续 } Debug.Log($"循环: {i}"); yield return new WaitForSeconds(0.5f); } Debug.Log("循环完成"); } // 使用 yield break IEnumerator LoopWithYieldBreak() { for (int i = 0; i < 5; i++) { if (i == 2) { yield break; // 立即终止整个协程 } Debug.Log($"循环: {i}"); yield return new WaitForSeconds(0.5f); } Debug.Log("这行永远不会执行"); // ❌ 不会执行 }

与普通break的区别

csharp

IEnumerator CompareWithBreak() { for (int i = 0; i < 5; i++) { if (i == 2) { break; // 只跳出循环,协程继续执行后面的代码 } Debug.Log($"循环内: {i}"); yield return null; } Debug.Log("循环后的代码"); // ✅ 这行会执行 yield return null; Debug.Log("协程结束"); // ✅ 这行也会执行 } IEnumerator CompareWithYieldBreak() { for (int i = 0; i < 5; i++) { if (i == 2) { yield break; // 立即终止整个协程 } Debug.Log($"循环内: {i}"); yield return null; } Debug.Log("循环后的代码"); // ❌ 这行不会执行 yield return null; Debug.Log("协程结束"); // ❌ 这行也不会执行 }

嵌套协程中的行为

csharp

IEnumerator ParentCoroutine() { Debug.Log("父协程开始"); // 启动子协程 yield return StartCoroutine(ChildCoroutine()); Debug.Log("子协程完成后执行"); // 注意这里! } IEnumerator ChildCoroutine() { Debug.Log("子协程第1步"); yield return null; Debug.Log("子协程第2步"); // 使用 yield return null yield return null; // 子协程暂停,但会恢复 // 或者使用 yield break // yield break; // 子协程立即终止 Debug.Log("子协程第3步"); // 如果前面是 yield break,这行不会执行 } // 情况1: 子协程使用 yield return null // 输出: // 父协程开始 // 子协程第1步 // (等待一帧) // 子协程第2步 // (等待一帧) // 子协程第3步 // 子协程完成后执行 // 情况2: 子协程使用 yield break // 输出: // 父协程开始 // 子协程第1步 // (等待一帧) // 子协程第2步 // 子协程完成后执行 <- 注意:父协程继续执行!

重要注意事项

1.资源清理问题

csharp

IEnumerator ProblematicCoroutine() { // 分配资源 var resource = new ExpensiveResource(); try { // 一些操作... if (shouldStop) { yield break; // ❌ 危险!可能导致资源泄漏 } // 更多操作... } finally { // 但 yield break 会跳过 finally 吗?让我们测试... } // 清理资源(如果 yield break,这行不会执行) resource.Dispose(); } // 更好的做法: IEnumerator BetterCoroutine() { var resource = new ExpensiveResource(); try { // 使用 using 语句确保清理 using (resource) { if (shouldStop) { yield break; // using 会确保 Dispose 被调用 } // 更多操作... } } finally { Debug.Log("finally 块执行"); // 注意:即使 yield break,finally 也会执行! } }

2.finally 块的行为

csharp

IEnumerator TestFinally() { try { Debug.Log("try 块开始"); yield return null; Debug.Log("try 块中间"); yield break; // 立即退出 Debug.Log("try 块结束 - 不会执行"); } finally { Debug.Log("finally 块执行"); // ✅ 这行会执行! } Debug.Log("协程最后 - 不会执行"); }

实用技巧

1.组合使用

csharp

IEnumerator SmartCoroutine() { for (int i = 0; i < 100; i++) { // 每10帧检查一次退出条件 if (i % 10 == 0 && ShouldExitEarly()) { yield break; } // 正常处理 ProcessFrame(i); // 每帧暂停 yield return null; } }

2.带返回值的协程

csharp

IEnumerator<int> CoroutineWithReturnValue() { yield return 1; yield return 2; if (someCondition) { yield break; // 提前结束,不再返回 3 } yield return 3; } // 使用: var enumerator = CoroutineWithReturnValue(); while (enumerator.MoveNext()) { Debug.Log(enumerator.Current); } // 如果提前 yield break,就不会输出 3

总结

  • yield return null:是协程的"暂停按钮",表示"等待一帧后继续"

  • yield break:是协程的"停止按钮",表示"立即结束,不再继续"

关键记忆点

  • 当你想要协程暂时等待时,使用yield return null

  • 当你想要协程完全终止时,使用yield break

  • yield break会跳过协程中后续所有代码,但finally 块仍会执行

  • 在循环中,yield break终止整个协程,而普通break只跳出当前循环

理解这两者的区别对于编写正确的协程逻辑至关重要,特别是在资源管理和错误处理方面。

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/6/10 11:28:55

MicMute:打造高效麦克风静音管理的桌面利器

MicMute&#xff1a;打造高效麦克风静音管理的桌面利器 【免费下载链接】MicMute Mute default mic clicking tray icon or shortcut 项目地址: https://gitcode.com/gh_mirrors/mi/MicMute 在当今远程办公和在线沟通日益频繁的时代&#xff0c;你是否曾经历过这些尴尬场…

作者头像 李华
网站建设 2026/6/10 11:22:17

轻量NLP模型之王:DeepSeek-R1-Distill-Qwen-1.5B

轻量NLP模型之王&#xff1a;DeepSeek-R1-Distill-Qwen-1.5B 1. 引言&#xff1a;为何轻量级NLP模型正成为边缘智能的关键 随着大模型在自然语言处理&#xff08;NLP&#xff09;领域的持续突破&#xff0c;模型参数规模不断攀升。然而&#xff0c;在真实应用场景中&#xff…

作者头像 李华
网站建设 2026/6/10 11:26:28

终极免费本地弹幕播放器BiliLocal完整使用指南

终极免费本地弹幕播放器BiliLocal完整使用指南 【免费下载链接】BiliLocal add danmaku to local videos 项目地址: https://gitcode.com/gh_mirrors/bi/BiliLocal BiliLocal是一款专为本地视频设计的开源弹幕播放器&#xff0c;能够为您的本地视频文件智能加载并显示弹…

作者头像 李华
网站建设 2026/6/10 15:08:08

Blender到OGRE导出器实战:解决游戏开发中的资产转换难题

Blender到OGRE导出器实战&#xff1a;解决游戏开发中的资产转换难题 【免费下载链接】blender2ogre Blender exporter for the OGRE 3D engine 项目地址: https://gitcode.com/gh_mirrors/bl/blender2ogre 作为一名游戏开发者&#xff0c;我经常面临这样的困境&#xff…

作者头像 李华
网站建设 2026/6/10 18:59:34

天若OCR本地版:高效离线文字识别工具使用全攻略

天若OCR本地版&#xff1a;高效离线文字识别工具使用全攻略 【免费下载链接】wangfreexx-tianruoocr-cl-paddle 天若ocr开源版本的本地版&#xff0c;采用Chinese-lite和paddleocr识别框架 项目地址: https://gitcode.com/gh_mirrors/wa/wangfreexx-tianruoocr-cl-paddle …

作者头像 李华
网站建设 2026/6/9 23:32:03

Arduino Uno R3开发板电源管理机制系统学习

深入理解Arduino Uno R3的电源系统&#xff1a;从入门到实战优化你有没有遇到过这样的情况&#xff1f;项目运行得好好的&#xff0c;突然Arduino板子“死机”了&#xff1b;或者上传程序时频繁断开连接&#xff1b;又或者接上电机后整个系统开始乱码、重启……这些问题&#x…

作者头像 李华