Unity协程(Coroutine)原理深入剖析再续

本文深入剖析Unity中的协程(Coroutine),讲解yield return, IEnumerator与Unity的StartCoroutine之间的关系。通过示例探讨了Cortoutine的扩展,包括返回值处理和错误捕获,并介绍了Cortoutine的锁机制,防止并发问题。文章还提供了代码示例,以加深对Unity协程工作原理的理解。" 111791828,10293975,webpack-dev-server配置http-proxy解决跨域问题,"['前端开发', 'JavaScript', 'webpack', '解决跨域']
摘要由CSDN通过智能技术生成

   本文主要分为三部分:

               1)yield return, IEnumerator  和 Unity StartCoroutine 的关系和理解

               2)Cortoutine 扩展——Extending Coroutines: Return Values and Error Handling

               3)Cortountine Locking

 

         总之,引用③的一句话:Coroutines – More than you want to know.

         

1)yield return, IEnumerator  和 Unity StartCoroutine 的关系和理解

          yield 和 IEnumerator都是C#的东西,前者是一个关键字,后者是枚举类的接口。对于IEnumerator 只引用②对 IEnumerable与IEnumerator区别 的论述:

先贴出 IEnumerable 和 IEnumerator的定义:

C#代码   收藏代码
  1. public interface IEnumerable  
  2. {  
  3.     IEnumerator GetEnumerator();  
  4. }  
  5.    
  6. public interface IEnumerator  
  7. {  
  8.     bool MoveNext();  
  9.     void Reset();  
  10.    
  11.     Object Current { get; }  
  12. }  

 IEnumerable和IEnumerator有什么区别?这是一个很让人困惑的问题(在很多forum里都看到有人在问这个问题)。研究了半天,得到以下几点认识:

         1、一个Collection要支持foreach方式的遍历,必须实现IEnumerable接口(亦即,必须以某种方式返回IEnumerator object)。

         2、IEnumerator object具体实现了iterator(通过MoveNext(),Reset(),Current)。

         3、从这两个接口的用词选择上,也可以看出其不同:IEnumerable是一个声明式的接口,声明实现该接口的class是“可枚举(enumerable)”的,但并没有说明如何实现枚举器(iterator);IEnumerator是一个实现式的接口,IEnumerator object就是一个iterator。

         4、IEnumerable和IEnumerator通过IEnumerable的GetEnumerator()方法建立了连接,client可以通过IEnumerable的GetEnumerator()得到IEnumerator object,在这个意义上,将GetEnumerator()看作IEnumerator object的factory method也未尝不可。

 

IEnumerator  是所有枚举数的基接口。   

         枚举数只允许读取集合中的数据。枚举数无法用于修改基础集合。   

         最初,枚举数被定位于集合中第一个元素的前面。Reset   也将枚举数返回到此位置。在此位置,调用   Current   会引发异常。因此,在读取   Current   的值之前,必须调用   MoveNext   将枚举数提前到集合的第一个元素。   

         在调用   MoveNext   或   Reset   之前,Current   返回同一对象。MoveNext   将   Current   设置为下一个元素。   

         在传递到集合的末尾之后,枚举数放在集合中最后一个元素后面,且调用   MoveNext   会返回   false。如果最后一次调用   MoveNext   返回   false,则调用   Current   会引发异常。若要再次将   Current   设置为集合的第一个元素,可以调用   Reset,然后再调用   MoveNext。   

         只要集合保持不变,枚举数就将保持有效。如果对集合进行了更改(例如添加、修改或删除元素),则该枚举数将失效且不可恢复,并且下一次对   MoveNext   或   Reset   的调用将引发   InvalidOperationException。如果在   MoveNext   和   Current   之间修改集合,那么即使枚举数已经无效,Current   也将返回它所设置成的元素。   

         枚举数没有对集合的独占访问权;因此,枚举一个集合在本质上不是一个线程安全的过程。甚至在对集合进行同步处理时,其他线程仍可以修改该集合,这会导致枚举数引发异常。若要在枚举过程中保证线程安全,可以在整个枚举过程中锁定集合,或者捕捉由于其他线程进行的更改而引发的异常。

 

Yield关键字

在迭代器块中用于向枚举数对象提供值或发出迭代结束信号。它的形式为下列之一⑥:

  yield return <expression_r>;

  yield break;

备注 :

  计算表达式并以枚举数对象值的形式返回;expression_r 必须可以隐式转换为迭代器的 yield 类型。

  yield 语句只能出现在 iterator 块中,该块可用作方法、运算符或访问器的体。这类方法、运算符或访问器的体受以下约束的控制:

  不允许不安全块。

  方法、运算符或访问器的参数不能是 ref 或 out。

  yield 语句不能出现在匿名方法中。

  当和 expression_r 一起使用时,yield return 语句不能出现在 catch 块中或含有一个或多个 catch 子句的 try 块中。

 

  yield return 提供了迭代器一个比较重要的功能,即取到一个数据后马上返回该数据,不需要全部数据装入数列完毕,这样有效提高了遍历效率。

 

Unity StartCoroutine

      Unity使用 StartCoroutine(routine: IEnumerator): Coroutine 启动协程,参数必须是 IEnumerator 对象。那么Unity在背后做什么神奇的处理呢?

      StartCoroutine函数的参数我一般都是通过传入一个返回值为 IEnumerator的函数得到的:

C#代码   收藏代码
  1. IEnumerator WaitAndPrint(float waitTime) {  
  2.     yield return new WaitForSeconds(waitTime);  
  3.     print("WaitAndPrint " + Time.time);  
  4. }  

       在函数内使用前面介绍 yield 关键字返回 IEnumerator 对象,Unity 中实现了 YieldInstruction 作为 yield 返回的基类,有 Cortoutine, WaitForSecondes, WaitForEndOfFrame, WaitForFixedUpdate, WWW 几个子类实现。StartCoroutine 将 传入的 IEnumerator 封装为 Coroutine 返回,引擎会对 Corountines 存储和检查 IEnumerator 的 Current值。

 

③枚举了 WWW ,WaitForSeconds , null 和 WaitForEndOfFrame 检查 Current值在MonoBebaviour生存周期的时间(没有WaitForFixedUpdate ,D.S.Qiu猜测是其作者成文是Unity引擎还没有提供这个实现):

 

       WWW - after Updates happen for all game objects; check the isDone flag. If true, call the IEnumerator's MoveNext() function;

       WaitForSeconds - after Updates happen for all game objects; check if the time has elapsed, if it has, call MoveNext();

       null or some unknown value - after Updates happen for all game objects; Call MoveNext();

       WaitForEndOfFrame - after Render happens for all cameras; Call MoveNext().

 

如果最后一个 yield return 的 IEnumerator 已经迭代到最后一个是,MoveNext 就会 返回 false 。这时,Unity就会将这个 IEnumerator 从 cortoutines list 中移除。

 

       所以很容易一个出现的误解:协程 Coroutines 并不是并行的,它和你的其他代码都运行在同一个线程中,所以才会在Update 和 Coroutine中使用 同一个值时才会变得线程安全。这就是Unity对线程安全的解决策略——直接不使用线程,最近Unity 5 将要发布说的很热,看到就有完全多线程的支持,不知道是怎么实现的,从技术的角度,还是很期待的哈。

 

       总结下: 在协程方法中使用 yield return 其实就是为了返回 IEnumerator对象,只有当这个对象的 MoveNext() 返回 false 时,即该 IEnumertator 的 Current 已经迭代到最后一个元素了,才会执行 yield return 后面的语句。也就是说, yield return 被会“翻译”为一个 IEnmerator 对象,要想深入了解这方面的更多细节,可以猛击⑤查看。

       根据⑤ C# in depth 的理解——C# 编译器会生成一个 IEnumerator 对象,这个对象实现的 MoveNext() 包含函数内所有 yield return 的处理,这里仅附上一个例子:

C#代码   收藏代码
  1. using System;  
  2. using System.Collections;  
  3.   
  4. class Test  
  5. {  
  6.     static IEnumerator GetCounter()  
  7.     {  
  8.         for (int count = 0; count < 10; count++)  
  9.         {  
  10.             yield return count;  
  11.         }  
  12.     }  
  13. }  

 C#编译器对应生成:

Cpp代码   收藏代码
  1. internal class Test  
  2. {  
  3.     // Note how this doesn't execute any of our original code  
  4.     private static IEnumerator GetCounter()  
  5.     {  
  6.         return new <GetCounter>d__0(0);  
  7.     }  
  8.   
  9.     // Nested type automatically created by the compiler to implement the iterator  
  10.     [CompilerGenerated]  
  11.     private sealed class <GetCounter>d__0 : IEnumerator<object>, IEnumerator, IDisposable  
  12.     {  
  13.         // Fields: there'll always be a "state" and "current", but the "count"  
  14.         // comes from the local variable in our iterator block.  
  15.         private int <>1__state;  
  16.         private object <>2__current;  
  17.         public int <count>5__1;  
  18.   
  19.         [DebuggerHidden]  
  20.         public <GetCounter>d__0(int <>1__state)  
  21.         {  
  22.             this.<>1__state = <>1__state;  
  23.         }  
  24.   
  25.         // Almost all of the real work happens here  
  26.         private bool MoveNext()  
  27.         {  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值