Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>It is possible, but it would be awkward and difficult to get right. The best way to make this happen is to use <a href="http://en.wikipedia.org/wiki/Coroutine" rel="nofollow noreferrer">coroutines</a>. The only mechanism in .NET that currently fits the coroutine paradigm is C#'s iterators via the <code>yield return</code> keyword. You <em>could</em> theorectically hack something together that allows the execution of a method to transition from one thread to another<sup>1</sup>. However, this would be nothing less than a blog worthy hack, but I do think it is possible.<sup>2</sup></p> <p>The next best option is to go ahead and upgrade to the <a href="http://msdn.microsoft.com/en-us/vstudio/async.aspx" rel="nofollow noreferrer">Async CTP</a>. 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 <code>await</code> keyword and some clever exploits that will also be included. The end result would look something like the follwing.</p> <pre><code>public async void SomeMethod() { // Do stuff on the calling thread. await ThreadPool.SwitchTo(); // Switch to the ThreadPool. // Do stuff on a ThreadPool thread now! await MyForm.Dispatcher.SwitchTo(); // Switch to the UI thread. // Do stuff on the UI thread now! } </code></pre> <p>This is just one of the many wicked cool tricks you can do with the new <code>await</code> keyword.</p> <hr> <p><sup>1</sup>The 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.</p> <p><sup>2</sup>You can see my answer <a href="https://stackoverflow.com/questions/5401567/how-to-implement-await-without-async-ctp/6712397#6712397">here</a> for one such attempt at mimicking the <code>await</code> keyword with iterators. The <a href="http://developer.mindtouch.com/Dream" rel="nofollow noreferrer">MindTouch Dream</a> framework is another, probably better, variation. The point is that it should be possible to cause the thread switching with some ingenious hacking.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload