Reputation: 827
I'm using this code in my windows phone 8 app and I never get a return from this method:
private static ObservableCollection<Product> _productList = null;
public ObservableCollection<Product> GetProductList()
{
LoadProducts().Wait();
return _productList;
}
public Product GetProductById(int id)
{
return _productList.FirstOrDefault(p => p.Id == id);
}
private static async Task LoadProducts()
{
_productList = new ObservableCollection<Product>();
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:15017/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//HERE I NEVER GET THE RESPONSE
HttpResponseMessage response = await client.GetAsync("api/products").ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
var products = await response.Content.ReadAsAsync<List<Product>>();
foreach (var product in products)
{
_productList.Add(new Product(){Description = product.Description, Id=product.Id, Name = product.Name});
}
}
}
}
Can someone please tell me why is it like that? I run this method from my ViewModel class to load data
Using @Stephen Cleary sollution http://msdn.microsoft.com/en-us/magazine/dn605875.aspx there is a problem:
In my View I have set:
<ListBox Grid.Row="1" x:Name="listBox" ItemsSource="{Binding DataSource.Result}"
Then in codeBehind:
this.DataContext = new ProductViewModel();
Then in ProductViewModel:
public AsyncTaskManager<ObservableCollection<Product>> DataSource { get; private set; }
AND:
this.DataSource = new AsyncTaskManager<ObservableCollection<Product>>(ProductRepository.LoadProducts());
And In AsyncTaskManager PropertyChanged is always null :(
Upvotes: 0
Views: 205
Reputation: 456322
The Wait
in your code is causing a deadlock issue that I describe in detail on my blog an in an MSDN article. In short, await
by default will capture a "context" (in this case, the UI context), and will resume the async
method in that context. However, when you block the UI thread by calling Wait
, then the UI thread cannot complete the async
method it's waiting for. Hence, deadlock.
Since you're using MVVM, I recommend you take a look at my MSDN article on asynchronous data binding. In summary, you'll need to first design what the view should look like without the data and show that, and then update the view when the data arrives.
Upvotes: 3
Reputation: 3683
Your emulator cannot bind to localhost
it must be an ip address of your pc.
That's the problem
Upvotes: 0