Sunday, July 17, 2011

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);

            });
        }
 

Read more:  More Wally - Wallace B. McClure
QR: threading-in-monotouch-iphone-ios-ftw.aspx

Posted via email from Jasper-Net