0

I would like to perform (4-5) background Json parsing from web. I've got class with static method:

EventsSingleton.GetPlaces();

Which return list. That's working so far. When I try to async all the operations:

public async Task<List<Places>> Test()
{

    var myTask = Task.Run(() => Test2());
    List<Places> result = await myTask;
    return result;
}


public List<Places> Test2()
{
      List<Places> listatest = EventsSingleton.GetPlaces();
      for (int i = 0; i <= 50; i++)
    {
        progressBar5.Dispatcher.Invoke(() => progressBar5.Value = i, DispatcherPriority.Background);
    }
    return listatest;
}

Everything is still ok by now, correctly returning list and setting progressbar. Problem came out when I tried to return that value to my page contructor (or to OnClickButton method). I'm trying to do:

 var list5 = Test().Result;

But after compilation my program doesn't even start. I thing that my list isn't prepared yet, but maybe that "await" should do the job?

bc291
  • 1,071
  • 11
  • 23
  • Change it to `var list5 = await Test();`. And change `OnClickButton` method to be asynchronous `private async void OnClickButton()... ` – Fabio Mar 25 '18 at 20:42
  • When you use Test().Result, Test() is executed on another thread on the pool, while the main thread waits for the result to complete and freezes. When the helper thread finishes, it attempts to return the result to the main thread, only to find it frozen. Thus you have a deadlock. Try to use await Test(); – M Bakardzhiev Mar 25 '18 at 20:43
  • Nice explanation: [Don't Block on Async Code](https://blog.stephencleary.com/2012/07/dont-block-on-async-code.html) – Fabio Mar 25 '18 at 20:45
  • Ok but when I'm doing var list5 = await Test(); I can't get the result because of(https://pasteboard.co/HdAizes.png) when trying to: var list5 = await Test().Result; – bc291 Mar 25 '18 at 20:48
  • Write `var list5 = await Test()` instead of `var list5 = await Test().Result` – M Bakardzhiev Mar 25 '18 at 20:49
  • @needtobe, Remove `.Result;` when call `Test` method with `await`. It should be: `var list = await Test();` – Fabio Mar 25 '18 at 20:49
  • Oh that's working. Thank you very much. I don't know why I repeatedly tried to use Result. – bc291 Mar 25 '18 at 20:50

0 Answers0