C# 由于数据集原因,表单加载时间过长

C# 由于数据集原因,表单加载时间过长,c#,mysql,winforms,C#,Mysql,Winforms,实际上,我的数据集源是mysql,这是我的代码 private void frmNewInstallment_Load_1(object sender, EventArgs e) { // TODO: This line of code loads data into the 'cricflip_RoyalResidencyDataSet.booked_homes' table. You can move, or remove it, as needed

实际上,我的数据集源是mysql,这是我的代码

 private void frmNewInstallment_Load_1(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'cricflip_RoyalResidencyDataSet.booked_homes' table. You can move, or remove it, as needed.
            this.booked_homesTableAdapter.Fill(this.cricflip_RoyalResidencyDataSet.booked_homes);


        }

但是加载表单仍然需要很长时间,我想消除这种延迟。是否有任何方法可以异步执行此操作

不要使用表单加载事件。创建后台工作程序,在表单加载事件期间,启动后台工作程序。让后台工作人员更新GUI,让用户知道它仍然很忙


榜样

表单加载
事件中执行繁重的操作是不可取的,我建议使用
线程/任务
来执行此操作

private void frmNewInstallment_Load_1(object sender, EventArgs e)
{
     // Start a thread to load data asynchronously.
     Thread t = new Thread(LoadData);
     t.Start();
}  


private void LoadData()
{
     this.booked_homesTableAdapter.Fill(this.cricflip_RoyalResidencyDataSet.booked_homes);

    // 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(() =>
        {
            // Update your UI controls.
        }));
    }
}

你不需要不同的线程。在从数据库加载数据期间,线程什么也不做——只等待数据库的响应

使用
async/await
方法,您将使用在等待响应期间释放的相同UI线程

Form.Load
eventhandler似乎是这个好地方

Load
eventhandler标记为
async
,并使数据库调用也异步

public async Task<DataTable> GetData()
{
    //Your load logic
}

private async void Form_Load(object sender, EventArgs e)
{
    this.ComboBox.DataSource = await GetData();
}
公共异步任务GetData() { //您的加载逻辑 } 私有异步无效表单加载(对象发送方,事件参数e) { this.ComboBox.DataSource=await GetData(); }

据我所知,async/await完全是为IO进程设计的


只有在计算/处理内存中已有的某些数据时,您才需要不同的线程。

Sir您能用后台工作程序实现我的代码吗?我实际上是个新手,如果可能的话,可以添加任何进度条或对话框,让你从一个新手成长为一个真正的程序员,这将是一个很好的练习。花半小时实际阅读链接。或者,等等,再想一想,是的,我愿意为你实施,我的费率是每小时80欧元。PM我了解详细信息。@Lectere链接只提供答案,但不是最好的答案(尽管我认为您的答案是正确的。因此,也许一点代码实际上可以为答案增加价值-不是说实现,而是一些代码。感谢您的回答,但在实现此组合框后,它仍然是空的将所有UI操作放在
BeginInvoke
block.if(InvokeRequired)中)//在本例中,这将返回
true
{BeginInvoke(新操作(()=>{this.comboBox1.DataSource=this.bookedHomeBindingSource;this.comboBox1.DisplayMember=“Client_name”;this.comboBox1.TabIndex=0;this.comboBox1.ValueMember=“Client_name”;})我想您的数据源应该是this.cricflip_RoyalResidentityDataset.booked_homes概念相同,在任何UI线程之外创建线程并开始更新progressbar。