Threading in Monotouch/iPhone/iOS FTW! - More Wally - Wallace B. McClure
in

MoreWally.com

Giving people what they want, More Wally. This is the technical and personal blog site of
Wallace B. (Wally) McClure.

This Blog

Syndication

News

Please goy buy 3-4 copies of my book on MonoTouch titled "Professional Android Programming with Mono for Android for .NET/C# Developers." They make great gifts all year round. Plus, I get about $.25 when you buy a copy.

Technical Sites

More Wally - Wallace B. McClure

This blog will have all kinds of posts about Wally McClure. In it, there will be tons of .NET and computer programming posts as well as Wally's views on life in general. As you might guess, this site and blog help you get More Wally in your life. What more could anyone want? iPhone, Android, MonoTouch, MonoDroid, Mobile, HTML5, .NET, ADO.NET, ASP.NET, AJAX, jQuery, jQuery Mobile, ASP.NET AJAX, and Windows Azure............follow me on twitter at Wally

Threading in Monotouch/iPhone/iOS FTW!

I was writing a sample for showing off some advanced features in Monotouch with the UITableView.  Specifically, I was showing off how to scale a UITableViewCell based on the content within the cell.  One of the items in the cell was a UIImage who's content is being pulled from the Internet.  I was doing this all synchronously.  Unfortunately, the sliding of the table was a little herky/jerky due to the synchronicity of the image download.  I knew I needed to pull this out of the UI thread and perform this on  background thread.  By using the threadpool, the problem has been resolved.  Here's what I did:

        public string TwitterImage{
            set {
                ThreadPool.QueueUserWorkItem(new WaitCallback(SetTwitterImage), value);
            }
        }
       
        private void SetTwitterImage(object state)
        {
            var img = Convert.ToString(state);
            NSUrl nsUrl = new NSUrl(img);
            NSData data = NSData.FromUrl(nsUrl);
            InvokeOnMainThread(delegate{
                  uitvccImage.Image = new UIImage(data);

            });
        }
 

FYI, if you manually create your own threads (in other words, use an actual Thread object), you will need to wrap your code in:

   using (var ns = new NSAutoReleasePool ()){  
      // Your code goes here.
    }

 

Published Jul 14 2011, 04:31 PM by wallym
Filed under: , ,

Comments

 

Dew Drop – July 15, 2011 | Alvin Ashcraft's Morning Dew said:

Pingback from  Dew Drop – July 15, 2011 | Alvin Ashcraft's Morning Dew

July 15, 2011 9:07 AM
2006 - Wallace B. McClure
Powered by Community Server (Non-Commercial Edition), by Telligent Systems