I Am Not Myself


Using System.Threading.Tasks On MonoTouch

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;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: