Android AsyncTask-like functionality in C# (.NET)-Collection of common programming errors

As you might know, Android’s SDK features a AsyncTask class which allows for code execution on a separate thread and result acquisition in the main (UI) thread. In short, something like this:

class AsyncTask
{
   void onPreExecute(...)
   {
       //Executed on the main thread BEFORE the secondary thread gets to work on anything.
   }

   void execute(...)
   {
       //This runs on the secondary thread.
   }

   void onPostExecute(...)
   {
       //This runs on the main thread AFTER the secondary thread finishes work. You get the result here in the form of some data type.
   }
}

Of course, this is just a rough scheme, but it should provide enough info on the AsyncTask if you’re not familiar with it. Basically, I’m looking for the same functionality in Microsoft’s .NET Framework.

Before I start working on my own classes to do this, I want to be sure there’s nothing that could allow me to get the desired result already in the framework. I’m using .NET 4.0. Perhaps some sort of ‘clever’ use of System.Threading.Tasks.Task? Have no idea, I’ll leave this to you.

In short, I want to pass some input to a function, run the code on a secondary thread, and on completion, update some UI elements via the main thread. Locking the main thread (via Task.Wait() for example) doesn’t work well with my requirements.

  1. You can achieve what you’re looking for using the Task class in .Net.

    Here’s what some code looks like that should help get you started:

    var task = Task.Factory.StartNew(() => YourMethodGoesHere());
    
    task.ContinueWith(t => UpdateYourUiInThisContinuation(),
                      TaskScheduler.FromCurrentSynchronizationContext());
    
    task.ContinueWith(t => HandleAnExceptionWhichTheTaskMayThrow(), 
                       TaskContinuationOptions.OnlyOnFaulted);
    

    That will schedule the YourMethodGoesHere() to run off the UI thread. The continuation, UpdateYourUiInThisContinuation() will be scheduled to run once the initial task completes, and the overload I used will force it to continue within the same synchronization context (UI thread, assuming this code is being called on the UI thread initially).

    The last continuation is good practice to handle any exceptions which code within the task may thrown. If you don’t handle it (there are other ways other than using this continuation), you’ll end up with an unhandled AggregateException.

Originally posted 2013-12-02 20:57:42.