So I was chatting with a colleague about fibers and turned up this paper from 2003 that describes a implementation of coroutines in C# using the Fiber API.
The implementation of Yield
in this paper was for .NET 1.1, so it predates the yield return
syntax that appeared in .NET 2.0.
It definitely looks, at first glance, that the implementation here is potentially faster and could scale across multiple CPUs rather well.
Has anyone used it?
I haven't used it, but I have an interest in the subject. Here's one nice implementation of coroutines in C# with a round-robin scheduler: http://www.bluebytesoftware.com/blog/PermaLink.aspx?guid=71235c5a-3753-4bab-bdb0-334ab439afaf
By the way, quoting wikipedia, "fibers describe essentially the same concept as coroutines". As far as I know, the closest thing to a coroutine (or a fiber) in C# are iterators. Actually, they are remarkably close to coroutines. Lippert posted several catches about iterators. Hopefully, none of them represent an serious problem for the purposes you need.
I have used yield-based "coroutines," and I have to say that they are a pain in the butt. The problem is, of course, that everywhere you want to use them, you're forced to use the yield syntax. Not only that, but unless you chain yields (parent yields child's yield), you can only ever nest your coroutines one level deep. This completely destroys one of the key benefits of coroutines (full stack save/restore).
I implemented a fiber-based coroutine system in C# and it worked wonderfully UNTIL I hit an exception. Unfortunately the .Net runtime stores a bunch of internal exception stuff in OS threads, which means that emulating multiple threads using OS fibers (and p/invoke) just won't work unless you'll never, ever, ever have an exception.
Coroutines, at very first glance catches my attention.. some days ago i was searching for workflow solution for parrallel AsyncWCF Method calls and what i found was really fascinating:
http://csharperimage.jeremylikness.com/2010/03/sequential-asynchronous-workflows-in.html
this article shows a very good use of coroutines to create/manage workflows in Silverlight application that consumes WCF using Async Pattern.
I don't know its speed w.r.t to iterators but to me its like an advanced form of subroutines that can be very helpful in mission critical tasks where a normal subroutine can't offer you the luxury to perform a task in parallel.
来源:https://stackoverflow.com/questions/1881473/fibers-in-c-are-they-faster-than-iterators-and-have-people-used-them