Using await with a TableAdapter

余生长醉 提交于 2019-12-04 16:01:29
Paul Batum

The problem is that TableAdapters don't have asynchronous Fill methods. This means to get your Fill to run without blocking the UI thread you will have to run on it a worker thread. The async CTP doesn't help you with this - it makes it easier to consume async APIs but it won't help if the async version of the API doesn't exist.

But running the fill on a worker thread should be as easy as spinning up a Task:

public Task FillAsync()
{
    return Task.Factory.StartNew( () =>
    {
        adapter1.Fill(ds1);
        adapter2.Fill(ds2);
        // etc
    });
}

Now where the async CTP will come in handy is if you need to do some additional work after the fills and you need that additional work to happen on the UI thread:

public async Task RebindUI()
{
    // Do stuff on UI thread

    // Fill datasets on background thread
    await FillAsync();

    // When fill is complete do some more work on the UI thread
    refreshControls();              
}

By default when running in a WinForms/WPF/Silverlight app, when you await it will resume on the UI thread, so refreshControls will be called on your UI thread after the Fill work is done on a background thread.

There's a sample that covers this here: (UI Responsiveness -> Responsive UI during CPU bound tasks)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!