我的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
。
1条答案
按热度按时间blpfk2vs1#
你的代码“死锁”了。这是Xamarin。Forms Q&A解释了这个概念。SQLite-NET-PCL Stuck on CreateTableAsync()。
底线:不要将
.Result
与async
方法一起使用。尤其是在构造函数中。相反,通过 Package 代码进入async
上下文。毛伊岛:
或者,如果
GetAllPlayersAsync
需要很长时间,则从后台线程调用它可能更安全: