Using System.Threading.Tasks On MonoTouch

Back to Listing

Using System.Threading.Tasks On MonoTouch

13 May, 2012

I ran into an issue this week where I was attempting to load data from a web service asynchronously using System.Threading.Tasks on MonoTouch. I was able to fire the task off but kept getting an error trying to update UI elements when callback was fired.

After a little beating my head against a wall, I took a walk and grew a neuron and this is what I came up with to resolve the issue. Note the call to InvokeOnMainThread.

private IEnumerable<Product> GetProducts(Position position)  
    return productsService.GetProductsNear(position);

private void BeginGetProducts()  
    var scheduler = TaskScheduler.FromCurrentSynchronizationContext();

    Task.Factory.StartNew(() => GetProducts(currentPosition))
            .ContinueWith(OnProducts, scheduler);

private void OnProducts(Task<IEnumerable<Product>> task)  
        InvokeOnMainThread(() => {
            this.products = task.Result;
Share this story

Bobby Johnson

About Author

I am a passionate engineer with an interest in shipping quality software, building strong collaborative teams and continuous improvement of my skills, team and the product.

comments powered by Disqus
Back to top