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()
{
	Activity.PushNetworkActive();
	var scheduler = TaskScheduler.FromCurrentSynchronizationContext();

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

private void OnProducts(Task<IEnumerable<Product>> task)
{
	if(task.IsFaulted)
		HandleException(productsTask.Exception);
	else 
	{
		InvokeOnMainThread(() => {
			this.products = task.Result;
			ShowProducts();
		});
	}
	Activity.PopNetworkActive();
}
Follow me on Mastodon!