c# - 在winforms中从数据库异步加载数据

标签 c#

很多时候我们在表单加载中使用数据库中的数据填充 UI,这就是表单卡住几秒钟的原因。所以我只想知道如何异步加载数据并在表单加载中填充 UI,结果我的表单不会卡住并且也会响应,但我不想使用后台工作类。请帮助我提供可以解决我的问题的示例代码。

谢谢

最佳答案

这是一个注释良好的示例代码:

示例:

// This method can be called on Form_Load, Button_Click, etc.
private void LoadData()
{
    // Start a thread to load data asynchronously.
    Thread loadDataThread = new Thread(LoadDataAsync);
    loadDataThread.Start();
}

// This method is called asynchronously
private void LoadDataAsync()
{
    DataSet ds = new DataSet();

    // ... get data from connection

    // Since this method is executed from another thread than the main thread (AKA UI thread),
    // Any logic that tried to manipulate UI from this thread, must go into BeginInvoke() call.
    // By using BeginInvoke() we state that this code needs to be executed on UI thread.

    // Check if this code is executed on some other thread than UI thread
    if (InvokeRequired) // In this example, this will return `true`.
    {
        BeginInvoke(new Action(() =>
        {
            PopulateUI(ds);
        }));
    }
}

private void PopulateUI(DataSet ds)
{
    // Populate UI Controls with data from DataSet ds.
}

关于c# - 在winforms中从数据库异步加载数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4479319/

相关文章:

c# - 我在为类的 List<T> 分配初始大小时遇到​​问题

c# - 在 Microsoft Teams 中看不到建议的操作

c# - 非阻塞 Assert 对应方

c# - 如何在 sitecore 规则 contenteditor 中编写 C# 代码

c# - 在 C# 中填充 List<byte> 时出现 OutOfMemoryException

C#一次删除多个按钮

c# - 向可空类型添加方法

c# - 我怎样才能让我的老板相信 ANSI C 不适合我们的新项目?

c# - WCF:没有为此对象定义无参数构造函数依赖注入(inject)简单注入(inject)器

c# - 从系统帐户为用户创建 ServiceAccountCredential