Is there any way I can abstract away what thread a particular delegate may execute on, such that I could execute it on the calling thread initially, but move execution to a background thread if it ends up taking longer than a certain amount of time?
Assume the delegate is written to be asynchronous. I’m not trying to take synchronous blocks and move them to background threads to increase parallelism, but rather I’m looking to increase performance of asynchronous execution by avoiding the overhead of threads for simple operations.
Basically I’m wondering if there’s any way the execution of a delegate or lambda can be paused, moved to another thread and resumed, if I could establish clear stack boundaries, etc.
I doubt this is possible, I’m just curious.
It is possible, but it would be awkward and difficult to get right. The best way to make this happen is to use coroutines. The only mechanism in .NET that currently fits the coroutine paradigm is C#’s iterators via the
yield returnkeyword. You could theorectically hack something together that allows the execution of a method to transition from one thread to another1. However, this would be nothing less than a blog worthy hack, but I do think it is possible.2The next best option is to go ahead and upgrade to the Async CTP. This is a feature that will be available in C# and which will allow you do exactly what you are asking for. This is accomplished elegantly with the proposed
awaitkeyword and some clever exploits that will also be included. The end result would look something like the follwing.This is just one of the many wicked cool tricks you can do with the new
awaitkeyword.1The only way you can actually inject the execution of code onto an existing thread is if the target is specifically designed to accept the injection in the form of a work item.
2You can see my answer here for one such attempt at mimicking the
awaitkeyword with iterators. The MindTouch Dream framework is another, probably better, variation. The point is that it should be possible to cause the thread switching with some ingenious hacking.