Activity Indicator is dismissed before images are loaded

Multi tool use
Activity Indicator is dismissed before images are loaded
I have a question. My activity Indicator dismisses before my images are finished loading from my api. Is it because the call to the api is async? If so, how can I make sure the call is done or the images are loaded on the screen before dismissing my activity indicator?
The activity indicator code in my XAML looks like this:
<ActivityIndicator IsRunning="{Binding IsBusy}"
IsVisible="{Binding IsBusy}"
VerticalOptions="Center"
HorizontalOptions="Center"/>
My property (which is located in viewmodel base):
private bool isBusy;
public bool IsBusy
{
get { return isBusy; }
set { SetProperty(ref isBusy, value); }
}
And this is the code where I set the property:
public override async void OnNavigatingTo(NavigationParameters navParams)
{
if(navParams.ContainsKey("query"))
{
var query = (string)navParams["query"];
IsBusy = true;
await DisplayImages(query);
IsBusy = false;
}
}
Thanks!
DisplayImages
Check that DisplayImages method contains async keyword.
– progpow
Jul 2 at 22:27
Just makes a call to an api endpoint and sets the object it gets to the property that it should bind to. It does contain async keyword.
– Euridice01
Jul 2 at 22:28
You need to use a background thread.
– Richardissimo
Jul 2 at 22:28
How? With this? "System.Threading.Tasks.Task.Run(() => { //Add your code here. }).ConfigureAwait(false);"
– Euridice01
Jul 2 at 22:29
2 Answers
2
I'm not at my computer, and it's tricky to do on this device, but here goes...
Option 1: BackgroundWorker
Async/await doesn't make it run on a background thread, you need the loading to occur on a background thread. And be aware that Tasks and threads are different.
Create a field on your class, type BackgroundWorker
. Hook up the DoWork event of that field to be a method containing:
BackgroundWorker
IsBusy = true;
DisplayImages(query);
IsBusy = false;
And where those lines used to be, call RunWorkerAsync
on your field. You can put the value of query
into a field so it can be used from the DoWork method.
RunWorkerAsync
query
Option 2: an actual thread
Put the 3 lines in a method called Load(string query)
. Where those lines used to be, do this:
Load(string query)
myNewThread = new Thread(() => Load(query));
myNewThread.Start();
I think myNewThread
needs to be a field so it doesn't get garbage collected.
myNewThread
@Euridice01 Edited answer to add another option.
– Richardissimo
Jul 3 at 6:05
Implement in your method using:
Device.BeginInvokeOnMainThread(async () =>
{
//load your images here
//Lastly set IsBusy to false
});
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Async/await doesn't make it run on a background thread. How is
DisplayImages
implemented?– Richardissimo
Jul 2 at 22:26