Sqlite.net异步 - 如何在Xamarin中使用?

时间:2015-02-18 13:36:18

标签: c# sqlite windows-phone-8 asynchronous 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

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

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

1 个答案:

答案 0 :(得分:3)

您的代码有问题:

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

TestDb是一种异步方法,您在没有await的情况下异步调用它。

这会在您离开TestDb事件代码后调用Click

我建议您await致电:

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