Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xamarin, wait for async function ends

In main file MainPage I have method OnAppearing contains two functions.

MainPage.cs

 protected override void OnAppearing()
        {
            DataBaseService.checkNoteAlarmTimeActive();
            this.loadNotes();                       
            base.OnAppearing();
        }

Unfortunately method loadNotes() is fired before method DataBaseService.checkNoteAlarmTimeActive(); ends. It makes some problem in my app. How to change it to this.loadNotes() wait to previous function ends job?

Thank you. Class DataBaseService with metod:

public static async void checkNoteAlarmTimeActive()
        {           
            List<Note> notes = await getTimeActiveNotes();

            foreach(Note note in notes)
            {
                if(note.AlarmTime < DateTime.Now)
                {
                    note.AlarmTimeActive = false;
                    updateRecord(note);
                }
            }
        }
public static async Task<List<Note>> getTimeActiveNotes()
        {
            var notes = await _dbConnect.Table<Note>().Where(i => i.AlarmTimeActive == true).ToListAsync();            
            return notes;
        }
like image 556
Klick Avatar asked Oct 20 '25 10:10

Klick


1 Answers

The short answer is that you add async and await.

protected async override void OnAppearing()
        {
            await DataBaseService.checkNoteAlarmTimeActive();
            this.loadNotes();                       
            base.OnAppearing();
        }
like image 95
Sean Sparkman Avatar answered Oct 22 '25 03:10

Sean Sparkman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!