取消DataAdapter.Fill() [英] Canceling DataAdapter.Fill()

查看:77
本文介绍了取消DataAdapter.Fill()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

场景:
我们有一个DataGridView附加到DataAdapter(数据表),我们在单独的线程(使用委托和beginInvoke)中使用(adapter.fill(query,datatable))将数据加载到数据表中,一旦数据被加载,我们就将该数据表附加到datagridview(在主线程中)

Scenario: We have a DataGridView which is attached to DataAdapter (datatable), we load the data in datatable using (adapter.fill(query, datatable)) in a separate thread (using delegate and beginInvoke) and once the data is loaded we attached that datatable to datagridview (in the main thread)

有没有一种方法可以检查fill()是否仍在执行并取消它。

Is there a way we can check if fill() is still executing and cancel it.

实际情况:
用户单击用户名,相应的数据将加载到datagrid中。有时,用户不耐烦,请单击另一个用户(这里我要取消以前的填充并开始新的填充)

Real scenario: User click on the user name and corresponding data is loaded in the datagrid. Sometime, user is impatient and click on the another user (here I want to cancel the previous fill and start a new fill)

更新:
DataApdaters(和两个DataTable),我们将一个数据表附加到datagridview并开始异步将数据加载到另一个数据表。加载数据时,我们只需将datagridview绑定到我们刚刚填充的DataTable(并开始异步加载以前的datable),这样UI就会始终获取当前数据(无需用户等待UI刷新或挂起)

UPDATE: We keep two DataApdaters (and two DataTables) and we attach one datatable to datagridview and start loading data to another datatable asynchronously. When data is loaded we simply bind the datagridview to DataTable which we just filled (and start loading the previous datable asynchronously) This way UI will always get the current data (without user waiting on UI to refresh or hang)

推荐答案

您可以向适配器构造函数提供SqlCommand并在其上调用Cancel方法。
有一个原始模板:

You can provide a SqlCommand to adapter constructor and invoke a Cancel method on it. There is a raw template :

class Model 
{
    private SqlCommand loadUserCommand;
    private DataTable userData;

    public void LoadUser(string userId) 
    {
        loadUserCommand = GetUserLoadCommandForUserID(userId);
        userData = new DataTable("userData");
        using (var adapter = new SqlDataAdapter(loadUserCommand)) 
        {
            adapter.Fill(userData);
        }
    }

    public void AbortLoadUser()
    {
        if (loadUserCommand!= null)
            loadUserCommand.Cancel();
    }


    private SqlCommand GetUserLoadCommandForUserID(string userId)
    {
        var connection = new SqlConnection("...");
        var command = connection.CreateCommand();
        ...
    }
}

这篇关于取消DataAdapter.Fill()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆