c# – Sqlite.net异步 – 如何在Xamarin中使用?

我为Android和Windows Phone创建了一个应用程序.对于数据访问,我使用sqllite.net async.我用PCL liblary,Xamarin Android项目和Windows Phone 8 silverligth项目创建了简单的示例解决方案.这是我在PCL中的DataService:

public  class DataService
{
     private sqliteAsyncConnection _dbConnection;
     public DataService(IsqlitePlatform platform, string path)
    {
        var connectionFactory = new Func<sqliteConnectionWithLock>
                (() => new sqliteConnectionWithLock(platform, new     sqliteConnectionString(path, true)));
        _dbConnection = new sqliteAsyncConnection(connectionFactory);
    }
    public async Task Initialize()
    {
        await _dbConnection.CreateTableAsync<Todo>().ContinueWith(t =>
        {
           Debug.WriteLine("Create");
        });
    }
    public async Task<int> AddNewTodo(Todo item)
    {
        var result = await _dbConnection.InsertAsync(item);
        return result;
    } 

    public async Task<List<Todo>> GetAllTodos()
    {
        var result = await _dbConnection.Table<Todo>().OrderByDescending(t => t.TimeStamp).ToListAsync();
        return result;
    }
    ....
  }

这是在Windows Phone中使用的:

    private async void ButtonBase_OnClick(object sender, RoutedEventArgs e)
    {
        var db = new DataService(new sqlitePlatformWP8(), "my.db");
        await db.Initialize();
        await db.AddNewTodo(new Todo {Text = "Hello world"});
        var items = await db.GetAllTodos();
        Debug.WriteLine("Count - {0}",items.Count);
    } 

Windows Phone中的输出

Create
Count - 1

没关系.调试是有效的.

这是在Xamarin Android中使用的:

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);

        // Get our button from the layout resource,
        // and attach an event to it
        Button button = FindViewById<Button>(Resource.Id.MyButton);

        button.Click += delegate
        {
            TestDb();
        };
    }

    private async void TestDb()
    {
        string documentsPath =        System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); 
        var path = Path.Combine(documentsPath, "my.db");
        var db = new DataService(new sqlitePlatformAndroid(), path);
        await db.Initialize();
        await db.AddNewTodo(new Todo { Text = "Hello world" });
        var items = await db.GetAllTodos();
        Console.WriteLine("count - {0}",items.Count);
    }

输出

 [0:] 
 Create
 [0:] Create
 02-18 00:46:01.167 I/mono-stdout(19234): Create
 count - 1
 02-18 00:46:01.675 I/mono-stdout(19234): count - 1

为什么不止一次被调用?调试不起作用.当我停止使用等待的代码时,下一步就是退出方法而不触及我的回叫或任何东西.

这是一个简单的例子,我不明白为什么会这样.也许我做错了什么.

解决方法:

您的代码有问题:

button.Click += delegate
{
    TestDb();
};

TestDb是一个异步方法,你在没有await的情况下异步调用它.

这将使您在离开Click事件代码调用TestDb.

我建议你等待电话:

button.Click += async delegate
{
    await TestDb();
};

相关文章

SQLite架构简单,又有Json计算能力,有时会承担Json文件/RES...
使用Python操作内置数据库SQLite以及MySQL数据库。
破解微信数据库密码,用python导出微信聊天记录
(Unity)SQLite 是一个软件库,实现了自给自足的、无服务器...
安卓开发,利用SQLite实现登陆注册功能