how can an async method be executed synchronously in Xamarin.Forms











up vote
1
down vote

favorite












I am building a screen for my app in xamarin.forms the caul is based on a tabbedpage which is built dynamically based on a list of objects which I get as a result of consuming a service.
After I call the method to consume the API that brings the list, I need to go through it based on certain data of it to fill an observable collection of viewmodels, which will be the tabs. The problem I have is that I do not know how to call the async method that consumes the API in a synchronized way so that the consumption of the API does not conflict with the operation of going through the list.
Then a fraction of the code of my ViewModel:



public MonitoringViewModel()
{
LoadThings();
Tabs = new ObservableCollection<MonitoringTabsViewModel>();
foreach (PcThing t in Things)
{
Tabs.Add(new MonitoringTabsViewModel(t.description));
}
}


private async void LoadThings()
{
Things = new List<PcThing>(await App.WebApiManager.GetCustomerThinksAsync());
}


What I get is that in xamarin live player the app after a few seconds go from the green signal to the red one without showing anything, and in the log of it I get this:
Target of GetEnumerator is null (NullReferenceException)










share|improve this question






















  • Please review this SO topic. We use it in Production and all works very well.
    – Alexander I.
    Nov 18 at 21:05










  • Best way to handle asynchronous code is to make the synchronous code async. Usually there is some kind of event that starts the process that you can mark as async void. As for calling asynchronous code in a constructor, maby this reply to a similar scenario could help?
    – Shazi
    Nov 18 at 22:07

















up vote
1
down vote

favorite












I am building a screen for my app in xamarin.forms the caul is based on a tabbedpage which is built dynamically based on a list of objects which I get as a result of consuming a service.
After I call the method to consume the API that brings the list, I need to go through it based on certain data of it to fill an observable collection of viewmodels, which will be the tabs. The problem I have is that I do not know how to call the async method that consumes the API in a synchronized way so that the consumption of the API does not conflict with the operation of going through the list.
Then a fraction of the code of my ViewModel:



public MonitoringViewModel()
{
LoadThings();
Tabs = new ObservableCollection<MonitoringTabsViewModel>();
foreach (PcThing t in Things)
{
Tabs.Add(new MonitoringTabsViewModel(t.description));
}
}


private async void LoadThings()
{
Things = new List<PcThing>(await App.WebApiManager.GetCustomerThinksAsync());
}


What I get is that in xamarin live player the app after a few seconds go from the green signal to the red one without showing anything, and in the log of it I get this:
Target of GetEnumerator is null (NullReferenceException)










share|improve this question






















  • Please review this SO topic. We use it in Production and all works very well.
    – Alexander I.
    Nov 18 at 21:05










  • Best way to handle asynchronous code is to make the synchronous code async. Usually there is some kind of event that starts the process that you can mark as async void. As for calling asynchronous code in a constructor, maby this reply to a similar scenario could help?
    – Shazi
    Nov 18 at 22:07















up vote
1
down vote

favorite









up vote
1
down vote

favorite











I am building a screen for my app in xamarin.forms the caul is based on a tabbedpage which is built dynamically based on a list of objects which I get as a result of consuming a service.
After I call the method to consume the API that brings the list, I need to go through it based on certain data of it to fill an observable collection of viewmodels, which will be the tabs. The problem I have is that I do not know how to call the async method that consumes the API in a synchronized way so that the consumption of the API does not conflict with the operation of going through the list.
Then a fraction of the code of my ViewModel:



public MonitoringViewModel()
{
LoadThings();
Tabs = new ObservableCollection<MonitoringTabsViewModel>();
foreach (PcThing t in Things)
{
Tabs.Add(new MonitoringTabsViewModel(t.description));
}
}


private async void LoadThings()
{
Things = new List<PcThing>(await App.WebApiManager.GetCustomerThinksAsync());
}


What I get is that in xamarin live player the app after a few seconds go from the green signal to the red one without showing anything, and in the log of it I get this:
Target of GetEnumerator is null (NullReferenceException)










share|improve this question













I am building a screen for my app in xamarin.forms the caul is based on a tabbedpage which is built dynamically based on a list of objects which I get as a result of consuming a service.
After I call the method to consume the API that brings the list, I need to go through it based on certain data of it to fill an observable collection of viewmodels, which will be the tabs. The problem I have is that I do not know how to call the async method that consumes the API in a synchronized way so that the consumption of the API does not conflict with the operation of going through the list.
Then a fraction of the code of my ViewModel:



public MonitoringViewModel()
{
LoadThings();
Tabs = new ObservableCollection<MonitoringTabsViewModel>();
foreach (PcThing t in Things)
{
Tabs.Add(new MonitoringTabsViewModel(t.description));
}
}


private async void LoadThings()
{
Things = new List<PcThing>(await App.WebApiManager.GetCustomerThinksAsync());
}


What I get is that in xamarin live player the app after a few seconds go from the green signal to the red one without showing anything, and in the log of it I get this:
Target of GetEnumerator is null (NullReferenceException)







c# .net xamarin.forms async-await tabbedpage






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 18 at 20:44









lavilaso

143




143












  • Please review this SO topic. We use it in Production and all works very well.
    – Alexander I.
    Nov 18 at 21:05










  • Best way to handle asynchronous code is to make the synchronous code async. Usually there is some kind of event that starts the process that you can mark as async void. As for calling asynchronous code in a constructor, maby this reply to a similar scenario could help?
    – Shazi
    Nov 18 at 22:07




















  • Please review this SO topic. We use it in Production and all works very well.
    – Alexander I.
    Nov 18 at 21:05










  • Best way to handle asynchronous code is to make the synchronous code async. Usually there is some kind of event that starts the process that you can mark as async void. As for calling asynchronous code in a constructor, maby this reply to a similar scenario could help?
    – Shazi
    Nov 18 at 22:07


















Please review this SO topic. We use it in Production and all works very well.
– Alexander I.
Nov 18 at 21:05




Please review this SO topic. We use it in Production and all works very well.
– Alexander I.
Nov 18 at 21:05












Best way to handle asynchronous code is to make the synchronous code async. Usually there is some kind of event that starts the process that you can mark as async void. As for calling asynchronous code in a constructor, maby this reply to a similar scenario could help?
– Shazi
Nov 18 at 22:07






Best way to handle asynchronous code is to make the synchronous code async. Usually there is some kind of event that starts the process that you can mark as async void. As for calling asynchronous code in a constructor, maby this reply to a similar scenario could help?
– Shazi
Nov 18 at 22:07














2 Answers
2






active

oldest

votes

















up vote
1
down vote













Since you are doing this in the constructor , I would try the following:



using System.Threading.Tasks;


The risk here is if you are not in control of the LoadThings completing, it can hang.



public MonitoringViewModel()
{
var task = Task.Run(async () => { await LoadThings();}
Task.WaitAll(task); //block and wait for task to complete





share|improve this answer





















  • Why Task.WaitAll?
    – Paulo Morgado
    Nov 18 at 23:39










  • Thank you very much, after many days fighting with this, your answer is the only thing that has worked for me, although I am concerned about the risk you are aiming at, could I please give some more reference on this and / or explain it in a little more detail?
    – lavilaso
    Nov 18 at 23:52










  • Task.WaitAll is just what Microsoft called it (may not be the best name), but basically it waits for all of the provided tasks to complete execution. You can pass it a single task (as I done above) or an array of tasks, but it will block any further progress until the associated task(s) have ended.
    – cylon
    Nov 19 at 16:32










  • Thanks, do you have any examples of how to do this with an exception control and timeout to control a time limit of completion of the task?
    – lavilaso
    Nov 21 at 17:45


















up vote
0
down vote













public async Task<List<PcThing>> LoadThings()
{
return await App.WebApiManager.GetCustomerThinksAsync();
}


And in your ViewModel



Things = LoadThings().GetAwaiter().GetResult();





share|improve this answer





















  • Thanks, although it does not work, I just tried it and I get the same result as when I tried to use App.ApiManager.GetCustomerThinksAsync (). Result, which is that the green signal in the xamarin live player never disappears and never starts the app and verifies With the breakpoints the app never executes the GetCutomerThinks method, I get to see the flow on it but the breakpoints within it are never reached. Any ideas ?
    – lavilaso
    Nov 18 at 21:29











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














 

draft saved


draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53365274%2fhow-can-an-async-method-be-executed-synchronously-in-xamarin-forms%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes








up vote
1
down vote













Since you are doing this in the constructor , I would try the following:



using System.Threading.Tasks;


The risk here is if you are not in control of the LoadThings completing, it can hang.



public MonitoringViewModel()
{
var task = Task.Run(async () => { await LoadThings();}
Task.WaitAll(task); //block and wait for task to complete





share|improve this answer





















  • Why Task.WaitAll?
    – Paulo Morgado
    Nov 18 at 23:39










  • Thank you very much, after many days fighting with this, your answer is the only thing that has worked for me, although I am concerned about the risk you are aiming at, could I please give some more reference on this and / or explain it in a little more detail?
    – lavilaso
    Nov 18 at 23:52










  • Task.WaitAll is just what Microsoft called it (may not be the best name), but basically it waits for all of the provided tasks to complete execution. You can pass it a single task (as I done above) or an array of tasks, but it will block any further progress until the associated task(s) have ended.
    – cylon
    Nov 19 at 16:32










  • Thanks, do you have any examples of how to do this with an exception control and timeout to control a time limit of completion of the task?
    – lavilaso
    Nov 21 at 17:45















up vote
1
down vote













Since you are doing this in the constructor , I would try the following:



using System.Threading.Tasks;


The risk here is if you are not in control of the LoadThings completing, it can hang.



public MonitoringViewModel()
{
var task = Task.Run(async () => { await LoadThings();}
Task.WaitAll(task); //block and wait for task to complete





share|improve this answer





















  • Why Task.WaitAll?
    – Paulo Morgado
    Nov 18 at 23:39










  • Thank you very much, after many days fighting with this, your answer is the only thing that has worked for me, although I am concerned about the risk you are aiming at, could I please give some more reference on this and / or explain it in a little more detail?
    – lavilaso
    Nov 18 at 23:52










  • Task.WaitAll is just what Microsoft called it (may not be the best name), but basically it waits for all of the provided tasks to complete execution. You can pass it a single task (as I done above) or an array of tasks, but it will block any further progress until the associated task(s) have ended.
    – cylon
    Nov 19 at 16:32










  • Thanks, do you have any examples of how to do this with an exception control and timeout to control a time limit of completion of the task?
    – lavilaso
    Nov 21 at 17:45













up vote
1
down vote










up vote
1
down vote









Since you are doing this in the constructor , I would try the following:



using System.Threading.Tasks;


The risk here is if you are not in control of the LoadThings completing, it can hang.



public MonitoringViewModel()
{
var task = Task.Run(async () => { await LoadThings();}
Task.WaitAll(task); //block and wait for task to complete





share|improve this answer












Since you are doing this in the constructor , I would try the following:



using System.Threading.Tasks;


The risk here is if you are not in control of the LoadThings completing, it can hang.



public MonitoringViewModel()
{
var task = Task.Run(async () => { await LoadThings();}
Task.WaitAll(task); //block and wait for task to complete






share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 18 at 22:55









cylon

113




113












  • Why Task.WaitAll?
    – Paulo Morgado
    Nov 18 at 23:39










  • Thank you very much, after many days fighting with this, your answer is the only thing that has worked for me, although I am concerned about the risk you are aiming at, could I please give some more reference on this and / or explain it in a little more detail?
    – lavilaso
    Nov 18 at 23:52










  • Task.WaitAll is just what Microsoft called it (may not be the best name), but basically it waits for all of the provided tasks to complete execution. You can pass it a single task (as I done above) or an array of tasks, but it will block any further progress until the associated task(s) have ended.
    – cylon
    Nov 19 at 16:32










  • Thanks, do you have any examples of how to do this with an exception control and timeout to control a time limit of completion of the task?
    – lavilaso
    Nov 21 at 17:45


















  • Why Task.WaitAll?
    – Paulo Morgado
    Nov 18 at 23:39










  • Thank you very much, after many days fighting with this, your answer is the only thing that has worked for me, although I am concerned about the risk you are aiming at, could I please give some more reference on this and / or explain it in a little more detail?
    – lavilaso
    Nov 18 at 23:52










  • Task.WaitAll is just what Microsoft called it (may not be the best name), but basically it waits for all of the provided tasks to complete execution. You can pass it a single task (as I done above) or an array of tasks, but it will block any further progress until the associated task(s) have ended.
    – cylon
    Nov 19 at 16:32










  • Thanks, do you have any examples of how to do this with an exception control and timeout to control a time limit of completion of the task?
    – lavilaso
    Nov 21 at 17:45
















Why Task.WaitAll?
– Paulo Morgado
Nov 18 at 23:39




Why Task.WaitAll?
– Paulo Morgado
Nov 18 at 23:39












Thank you very much, after many days fighting with this, your answer is the only thing that has worked for me, although I am concerned about the risk you are aiming at, could I please give some more reference on this and / or explain it in a little more detail?
– lavilaso
Nov 18 at 23:52




Thank you very much, after many days fighting with this, your answer is the only thing that has worked for me, although I am concerned about the risk you are aiming at, could I please give some more reference on this and / or explain it in a little more detail?
– lavilaso
Nov 18 at 23:52












Task.WaitAll is just what Microsoft called it (may not be the best name), but basically it waits for all of the provided tasks to complete execution. You can pass it a single task (as I done above) or an array of tasks, but it will block any further progress until the associated task(s) have ended.
– cylon
Nov 19 at 16:32




Task.WaitAll is just what Microsoft called it (may not be the best name), but basically it waits for all of the provided tasks to complete execution. You can pass it a single task (as I done above) or an array of tasks, but it will block any further progress until the associated task(s) have ended.
– cylon
Nov 19 at 16:32












Thanks, do you have any examples of how to do this with an exception control and timeout to control a time limit of completion of the task?
– lavilaso
Nov 21 at 17:45




Thanks, do you have any examples of how to do this with an exception control and timeout to control a time limit of completion of the task?
– lavilaso
Nov 21 at 17:45












up vote
0
down vote













public async Task<List<PcThing>> LoadThings()
{
return await App.WebApiManager.GetCustomerThinksAsync();
}


And in your ViewModel



Things = LoadThings().GetAwaiter().GetResult();





share|improve this answer





















  • Thanks, although it does not work, I just tried it and I get the same result as when I tried to use App.ApiManager.GetCustomerThinksAsync (). Result, which is that the green signal in the xamarin live player never disappears and never starts the app and verifies With the breakpoints the app never executes the GetCutomerThinks method, I get to see the flow on it but the breakpoints within it are never reached. Any ideas ?
    – lavilaso
    Nov 18 at 21:29















up vote
0
down vote













public async Task<List<PcThing>> LoadThings()
{
return await App.WebApiManager.GetCustomerThinksAsync();
}


And in your ViewModel



Things = LoadThings().GetAwaiter().GetResult();





share|improve this answer





















  • Thanks, although it does not work, I just tried it and I get the same result as when I tried to use App.ApiManager.GetCustomerThinksAsync (). Result, which is that the green signal in the xamarin live player never disappears and never starts the app and verifies With the breakpoints the app never executes the GetCutomerThinks method, I get to see the flow on it but the breakpoints within it are never reached. Any ideas ?
    – lavilaso
    Nov 18 at 21:29













up vote
0
down vote










up vote
0
down vote









public async Task<List<PcThing>> LoadThings()
{
return await App.WebApiManager.GetCustomerThinksAsync();
}


And in your ViewModel



Things = LoadThings().GetAwaiter().GetResult();





share|improve this answer












public async Task<List<PcThing>> LoadThings()
{
return await App.WebApiManager.GetCustomerThinksAsync();
}


And in your ViewModel



Things = LoadThings().GetAwaiter().GetResult();






share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 18 at 21:03









Bruno Caceiro

1,97211121




1,97211121












  • Thanks, although it does not work, I just tried it and I get the same result as when I tried to use App.ApiManager.GetCustomerThinksAsync (). Result, which is that the green signal in the xamarin live player never disappears and never starts the app and verifies With the breakpoints the app never executes the GetCutomerThinks method, I get to see the flow on it but the breakpoints within it are never reached. Any ideas ?
    – lavilaso
    Nov 18 at 21:29


















  • Thanks, although it does not work, I just tried it and I get the same result as when I tried to use App.ApiManager.GetCustomerThinksAsync (). Result, which is that the green signal in the xamarin live player never disappears and never starts the app and verifies With the breakpoints the app never executes the GetCutomerThinks method, I get to see the flow on it but the breakpoints within it are never reached. Any ideas ?
    – lavilaso
    Nov 18 at 21:29
















Thanks, although it does not work, I just tried it and I get the same result as when I tried to use App.ApiManager.GetCustomerThinksAsync (). Result, which is that the green signal in the xamarin live player never disappears and never starts the app and verifies With the breakpoints the app never executes the GetCutomerThinks method, I get to see the flow on it but the breakpoints within it are never reached. Any ideas ?
– lavilaso
Nov 18 at 21:29




Thanks, although it does not work, I just tried it and I get the same result as when I tried to use App.ApiManager.GetCustomerThinksAsync (). Result, which is that the green signal in the xamarin live player never disappears and never starts the app and verifies With the breakpoints the app never executes the GetCutomerThinks method, I get to see the flow on it but the breakpoints within it are never reached. Any ideas ?
– lavilaso
Nov 18 at 21:29


















 

draft saved


draft discarded



















































 


draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53365274%2fhow-can-an-async-method-be-executed-synchronously-in-xamarin-forms%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Costa Masnaga

Fotorealismo

Sidney Franklin