前一陣自己看了《unity指令碼程式設計》其中講到了unity中協程的實現原理,講的比較難懂。我總結了給個基礎點的。
yield 關鍵字向編譯器指示它所在的方法是迭代器塊。 編譯器生成乙個類來實現迭代器塊中表示的行為。 在迭代器塊中,yield 關鍵字與 return 關鍵字結合使用,向列舉器物件提供值。 這是乙個返回值,例如,在 foreach 語句的每一次迴圈中返回的值。 yield 關鍵字也可與 break 結合使用,表示迭代結束。——msdn
msdn講的有點抽象,下面看看**
using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.threading;
using system.threading.tasks;
namespace
yieldtest
}class
feige}}
}}
結果:
返回的結果是:0
返回的結果是:1
返回的結果是:2
返回的結果是:3
返回的結果是:4
返回的結果是:5
返回的結果是:6
返回的結果是:7
返回的結果是:8
返回的結果是:9
using system;
using system.collections;
using system.collections.generic;
using system.linq;
using system.text;
using system.threading;
using system.threading.tasks;
namespace
yieldtest
console.readline();
}class
feige}}
}}
using system.collections;
using system.collections.generic;
namespace com.coroutine
}internal
coroutine()
internal
coroutine(ienumerator routine)
internal
bool
movenext()
else
if (m_routine.movenext())
else
}else
if (m_routine.movenext())
else}}
// use this as a template for functions like waitforseconds()
public
class waitforcount : coroutine
ienumerator count()}}
// use this as the base class for enabled coroutines
public
class coroutinemanager
// call this every frame
public
void
processcoroutines()
else
if (m_coroutines.count > 1)
else}}
}}
c# yield關鍵字的用法 協程(四)原理
出處 協程,又稱微執行緒和纖程等,據說源於 simula 和 modula 2 語言 我沒有深究,有錯請指正 現代程式語言基本上都有支援,比如 lua ruby 和最新的 google go,當然也還有最近很讓我驚豔的 falcon。協程是使用者空間執行緒,作業系統其存在一無所知,所以需要使用者自己...
協程(一)原理
賴勇浩 協程,又稱微執行緒和纖程等,據說源於 simula 和 modula 2 語言 我沒有深究,有錯請指正 現代程式語言基本上都有支援,比如 lua ruby 和最新的 google go,當然也還有最近很讓我驚豔的 falcon。協程是使用者空間執行緒,作業系統其存在一無所知,所以需要使用者自...
Lua協程實現原理
api 傳入引數 返回值 說明 api傳入引數 返回值說明 create f 函式,作為協程執行的主函式 返回建立的協程 如果還需要執行,需要使用resume操作 resume co,val1,傳入第乙個引數是create函式返回的協程,剩下的引數是傳遞給協程執行的引數。分兩種情況,resume成功...