views:

190

answers:

2
+9  Q: 

Coroutines in C#

I am looking to implement co-routines (user schedualed threads) in c#. When using c++ I was previously using fibers. As I see on the internet fibers do not exist in C#. I would like to get simillar functionality.

Is there any "right" way to implement coroutines in c#?

I have thought of implementing this using threads that aqcuire a single exection mutex + 1 one schedualer thread which releases this mutex for each coroutine. But this seems very costly (it forces a context switch between each coroutine)

I have also seen the yeild iterator functionality, but as I understand you can't yeild within an internal function (only in the original ienumerator function). So this does me little good.

+3  A: 

I believe that you should look at the the Reactive Extensions for .NET. For example coroutines can be simulated using iterators and the yield statement.

However you may want to read this SO question too.

Preet Sangha
+1  A: 

Here is an example of using threads to implement coroutines:

So I cheat. I use threads, but I only let one of them run at a time. When I create a coroutine, I create a thread, and then do some handshaking that ends with a call to Monitor.Wait(), which blocks the coroutine thread — it won’t run anymore until it’s unblocked. When it’s time to call into the coroutine, I do a handoff that ends with the calling thread blocked, and the coroutine thread runnable. Same kind of handoff on the way back.

Those handoffs are kind of expensive, compared with other implementations. If you need speed, you’ll want to write your own state machine, and avoid all this context switching. (Or you’ll want to use a fiber-aware runtime — switching fibers is pretty cheap.) But if you want expressive code, I think coroutines hold some promise.

SLaks