sqlite 表创建正在停止,没有引发异常

ljsrvy3e  于 2022-11-14  发布在  SQLite
关注(0)|答案(1)|浏览(192)

我的PlayerService类:

public static class PlayerService
    { 
        private static SQLiteAsyncConnection db;

        /// <summary>
        /// Creates database
        /// if Its created already it will use that instance
        /// </summary>
        /// <returns></returns>
        static async Task Init()
        {
            if(db != null) 
                return;

            db = new SQLiteAsyncConnection(DatabaseConstants.DatabasePath);
            await db.CreateTableAsync<Player>();
        }

        /// <summary>
        /// Adds player to the database
        /// </summary>
        /// <param name="playerName"></param>
        /// <param name="playerAlias"></param>
        /// <param name="playerTeam"></param>
        /// <returns>id</returns>
        public static async Task AddPlayerAsync(string playerName, string playerAlias, string playerTeam = null)
        {
            await Init();
            var player = new Player
            {
                Name = playerName, Alias = playerAlias, Team = playerTeam
            };
            await db.InsertAsync(player);
        }

数据库在Init()中创建,但在异步db.CreateTableAsync<Player>()上暂停,不引发异常。
查看模型:

public partial class ManagePlayersPageViewModel : ObservableObject
    {
        /// <summary>
        /// List of players being displayed 
        /// </summary>
        [ObservableProperty] private ObservableCollection<Player> players;

        public ManagePlayersPageViewModel()
        {
            Players = PlayerService.GetAllPlayersAsync().Result.ToObservableCollection();
        }

我已经清理和重建,更新了依赖项,并拥有raw.bundle.green

blpfk2vs

blpfk2vs1#

你的代码“死锁”了。这是Xamarin。Forms Q&A解释了这个概念。SQLite-NET-PCL Stuck on CreateTableAsync()
底线:不要将.Resultasync方法一起使用。尤其是在构造函数中。相反,通过 Package 代码进入async上下文。

毛伊岛

MainThread.BeginInvokeOnMainThread( async () =>
  {  // On MainThread.
    var players1 = await PlayerService.GetAllPlayersAsync();
    Players = players1.ToObservableCollection();
  });

或者,如果GetAllPlayersAsync需要很长时间,则从后台线程调用它可能更安全:

Task.Run( async () =>
  {  // On background thread.
    var players1 = await PlayerService.GetAllPlayersAsync();
    // Because Players affects UI, safest to get back on MainThread:
    MainThread.BeginInvokeOnMainThread( async () =>
      {  // On MainThread.
        Players = players1.ToObservableCollection();
      });
  });

相关问题