6

A common task is to do something in the background thread, then when done, pass the results to the UI thread and inform the user.

I understand there are two common ways:

I can use the TPL:

var context = TaskScheduler.FromCurrentSynchronizationContext ();

Task.Factory.StartNew (() => {
    DoSomeExpensiveTask();
    return "Hi Mom";
}).ContinueWith (t => { 
    DoSomethingInUI(t.Result);             
}, context);

Or the Older ThreadPool:

    ThreadPool.QueueUserWorkItem ((e) => {
          DoSomeExpensiveTask();
      this.InvokeOnMainThread (() => {
             DoSomethingInUI(...);
      });
});

Is there a recommended way to go when using MonoTouch to build iOS apps?

bryanmac
  • 38,941
  • 11
  • 91
  • 99
Ian Vink
  • 66,960
  • 104
  • 341
  • 555

2 Answers2

2

While I prefer the syntax of Task Parallel Library the ThreadPool code base is older (in both Mono and MonoTouch) so you're more likely to find documentation for it and less likely to hit a bug.

poupou
  • 43,413
  • 6
  • 77
  • 174
  • Is the ThreadPool code base still the more stable option or are they both equally stable at this point? – foldinglettuce Apr 30 '13 at 19:59
  • Pretty sure it's quite comparable today... at least I'm not aware of any remaining bug. Right now a lot of testing is being done with Mono 3.0 (Xamarin.iOS 6.3 betas) for the async support. – poupou Apr 30 '13 at 20:09
1

According to this document, mono touch provides access to ThreadPool and Thread:

The MonoTouch runtime gives access to developers to the .NET threading APIs, both explicit use of threads (System.Threading.Thread, System.Threading.ThreadPool) as well as implicitly when using the asynchronous delegate patterns or the BeginXXX methods.

http://docs.xamarin.com/ios/advanced_topics/threading

Also, you should call InvokeOnMainThread to update your UI.

bryanmac
  • 38,941
  • 11
  • 91
  • 99