Coffeehouse Post

Single Post Permalink

View Thread: Hey C# Team..
  • User profile image

    BlackTiger wrote:
    IMHO, "threadable { }" block would be more useful. This block can mean "run enclosed code on different thread (or even core?) if possible"

    You can already do this with just a little bit of your own "behind the scenes" code.

    Something like:

    void FancyButtonClicked()
       // This is called on the UI thread

       // Some local variables
       int someVar = 0;
       m_myFancyButton.Enabled = false;

       // Do something on a background thread, without blocking the UI
          // Do some process intensive task here on the background task...
          // it is ok to use someVar in this background thread...

       // Background thread is now done
       m_resultLabel.Text = someVar.ToString();
       m_myFancyButton.Enabled = true;

    Then, you have to create the DoBackgroundTask method to take a delegate as a parameter.  It takes this delegate and uses the tread pooling functionality to schedule it on a pooled thread.  It also has the logic to know when that delegate ended, and spins around in a loop doing Application.DoEvents (this ensures you UI stays responsive) until the delegate running on the pool thread finishes.  Yes, you need to do a little bit of upfront work to make the functionality work, but once you have DoBackroundTask working it is extremely easy to use the functionality anywhere in your code, such as the example I gave above.  The language automatically creates a reference to the someVar variable and it is visible inside the block of code executing on the background thread, and any changes will be reflected back to the code outside the block of background code. 

    I actually have a version of DoBackgoundTask that blocks the calling thread and one that does not block the calling thread.  Very useful.