views:

205

answers:

2

Is it at all possible in the middle of a function execution to set a pointer to the current stack (to be picked up later) and then release the current thread (without unwinding the call stack) and give it back to the thread pool? And then, have another thread pick up where that thread left off? I know it would mean that someone calling into the function would not know that the current thread context would have changed, and it would probably involve writing some custom IL code to do something like this, but is there ANY way to do this?

+8  A: 

No, a stack is part of the state of a thread. You can use asynchronous workflows to do this sort of thing (and the CCR makes this easier) but you can't just give the thread back to the thread pool.

You could write a thread pool which did do this, but it would be a bad idea IMO - it would be the thread pool equivalent of calling Application.DoEvents IMO.

Jon Skeet
+4  A: 

What you are describing is delimited continuations. Sadly, the CLR has no support for this, and cannot be implemented in managed code (not even mixed code) with any tricks I know of.

Currently, I need this functionality in IronScheme. There are ways to create this kind of functionality on the CLR, by writing a compiler that does CPS conversion, but that causes a host of interoperability issues (you cannot call .NET functions directly, etc).

I have made some experiments with CPS conversion in IronScheme, but my current compiler is not really suited for this, and performs rather slow.

leppie