Green threads in .NET

7.4k Views Asked by At

Green threads were introduced in Erlang and probably all languages based on it know them, also in go (gorutines). Then afaik they were removed from rust.

My questions:

  • How would one implement green threads in .NET? Are there some caveats that prevent current .NET runtime from implementing them?
  • Does it even makes sense in terms of performance? We have a quite lightweight Task and in (near) future we will have even ValueType Task (more suitable for some scenarios)...
3

There are 3 best solutions below

3
SACn On

In computer programming, green threads are threads that are scheduled by a runtime library or virtual machine (VM) instead of natively by the underlying operating system. Managed Threads written with NET Framework will be scheduled by framework but whatever be the case Windows OS will be running beneath and attaching threads to CPU (as NET requires Windows).

0
Nick Cox On

This is super old but worth pointing out: F# has lightweight user-mode threads built in via MailboxProcessor.

0
Marc Gravell On

How would one implement green threads in .NET? Are there some caveats that prevent current .NET runtime from implementing them?

In the .NET runtime, by layering a virtual thread on top of OS threads, and dealing with all the side-effects / niche cases (persisting stack-frames, dealing with affinity, and a lot more); it has recently been achieved in Java, and key folks in .NET have been investigating it.

Does it even makes sense in terms of performance? We have a quite lightweight Task and in (near) future we will have even ValueType Task (more suitable for some scenarios)...

This is a tricky one to answer without experimenting; green threads have the advantage that it would reach a lot more code, at once; but that's also a disadvantage in terms of risk / complexity. The machinery involved in async/await is not trivial, so if that can be elided: great! But in some ways, it is simply moved, albeit it to specialized code that could be heavily optimized. But as with all performance questions, the answer is in the numbers, and you can't get numbers without an experiment.