Xamarin,等待异步函数结束

标签 xamarin async-await

在主文件 MainPage 中,我有方法 OnAppearing 包含两个函数。

MainPage.cs

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

不幸的是,方法 loadNotes() 在方法 DataBaseService.checkNoteAlarmTimeActive(); 结束之前被触发。这在我的应用程序中造成了一些问题。 如何将其更改为 this.loadNotes() 等待上一个函数结束作业?

谢谢。 类 DataBaseService 方法:

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;
        }

最佳答案

简短的答案是添加 async 和 wait。

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

关于Xamarin,等待异步函数结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45720432/

相关文章:

c# - 如何在 SQLite.net 中查询 View ?

带有 2 行标签的 Xamarin.Forms ListView ?

c# - 当 Controller Action 同步时,有什么理由使用异步/等待吗?

android - Kotlin Coroutines 在 Android 中的正确方式

ios - Xamarin - iOS - 查找自动锁屏时间

c# - 如何删除 UIButton 设置的默认约束?

c# - Visual Studio 2017 社区、Xamarin、WatchOS。无法构建最简单的 watch 应用程序

node.js - mongoose.connection.collections.collection.drop() 每隔一段时间就会抛出错误

c# - 使用 EF6 从数据库中选择大量数据异步

javascript - 如何在其他 try block 中访问 try block 中的变量?