【问题标题】:form taking too long to load due to dataset由于数据集,表单加载时间过长
【发布时间】:2016-10-04 22:43:38
【问题描述】:

其实我的数据集源是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);


        }

但仍然需要很长时间才能加载我想消除延迟的表单。有什么方法可以异步执行此操作。

【问题讨论】:

    标签: c# mysql winforms


    【解决方案1】:

    不建议在Form_Load 事件中执行繁重的操作,我建议使用thread/task 来执行此操作。

    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.
            }));
        }
    }
    

    【讨论】:

    • 感谢您的回答,但实施此组合框后仍然为空
    • 将所有 UI 操作放在 BeginInvoke 块中。
    • if (InvokeRequired) // 在本例中,这将返回 true。 { BeginInvoke(new Action(() => { this.comboBox1.DataSource = this.bookedhomesBindingSource; this.comboBox1.DisplayMember = "Client_name"; this.comboBox1.TabIndex = 0; this.comboBox1.ValueMember = "Client_name"; } )); }
    • 我猜你的数据源应该是this.cricflip_RoyalResidencyDataSet.booked_homes
    • 概念相同,创建线程并开始在任何 UI 线程之外更新进度条。
    【解决方案2】:

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

    示例; https://msdn.microsoft.com/en-us/library/cc221403(v=vs.95).aspx

    【讨论】:

    • 先生,您能用后台工作人员为我的代码实现吗?我实际上是新手,如果可能的话,不要添加任何进度条或对话框
    • 不,对于您从新手成长为真正的程序员,这将是一个很好的练习。花半小时实际阅读链接。或者,等等,再想一想,是的,我愿意为你做一个实施,我的费率是每小时 80 欧元。私信我了解详情。
    • @Lectere Link 仅回答虽然不是最好的答案(尽管我认为你的回答是合适的。所以,也许一点代码实际上可以为答案增加价值 - 而不是每个实现说,但是一些代码。
    【解决方案3】:

    您不需要为此使用不同的线程。在从数据库线程加载数据期间,什么都不做 - 只等待来自数据库的响应。

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

    Form.Load eventhandler 似乎适合这个

    Load 事件处理程序标记为 async 并使您的数据库也调用异步。

    public async Task<DataTable> GetData()
    {
        //Your load logic
    }
    
    private async void Form_Load(object sender, EventArgs e)
    {
        this.ComboBox.DataSource = await GetData();
    }
    

    Asynchronous Programming with async and await (C#)

    据我了解,async/await 是专为 IO 进程设计的。

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

    【讨论】:

      猜你喜欢
      • 2021-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-23
      • 2016-06-20
      • 2016-02-17
      • 1970-01-01
      相关资源
      最近更新 更多