问题描述
我最近开始使用异步CTP,虽然我发现它对自编码类等非常有用,但是在尝试使用生成的代码(尤其是生成的TableAdapters)实现它时遇到了一些麻烦当您使用数据集时.
I recently began using the Async CTP and while I have found it quite useful with Self Coded classes and the like, I have run into a bit of a snag when trying to implement it with Generated Code, specifically the TableAdapters that are generated when you work with a Dataset.
我有一个使用.Fill调用的应用程序,用于填充DataGrid和Databindings.由于.Fill块和我的用户需要能够在进行此操作时与应用程序进行交互,因此我认为Async CTP是理想的解决方案.
I have an application that uses .Fill calls quite a bit to populate DataGrids and Databindings. Since .Fill blocks and my users need to be able to interact with the application while this is going on, I see the Async CTP to be an Ideal solution.
不幸的是,我似乎无法在无需自己编写代码的情况下将它与生成的TableAdpters一起使用.我有什么选择?
Unfortunately, I cannot seem to use it with the generated TableAdpters without having to code them myself. What are my options?
推荐答案
问题是TableAdapter没有异步Fill方法.这意味着要使Fill能够运行而不会阻塞UI线程,您将不得不在其上运行辅助线程.异步CTP对此无济于事-它使使用异步API更加容易,但是如果API的异步版本不存在,它将无济于事.
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
});
}
现在,异步CTP可以派上用场了,如果您需要在填充后执行一些其他工作,并且需要在UI线程上进行其他工作:
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();
}
默认情况下,在WinForms/WPF/Silverlight应用程序中运行时,当您等待时它将在UI线程上恢复,因此在后台线程上完成Fill工作后,将在UI线程上调用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.
此处有一个示例:(UI响应-> CPU绑定任务期间的响应UI)
There's a sample that covers this here:(UI Responsiveness -> Responsive UI during CPU bound tasks)
这篇关于与TableAdapter一起使用await的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!