后台工作者尝试 [英] Background worker attempt

查看:254
本文介绍了后台工作者尝试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是函数的原始方式:

    void fillLiguanea()
    {
        items = new List<string>();
        this.liguanea_Lane2TableAdapter.Fill(this.pharmaciesDataSet3.Liguanea_Lane2);
        try
        {

            string connectionString = "Data Source=LPMSW09000012JD\\SQLEXPRESS;Initial Catalog=Pharmacies;Integrated Security=True";
            SqlConnection con = new SqlConnection(connectionString);
            con.Open();
            string query = "SELECT * FROM dbo.Liguanea_Lane2";
            SqlCommand cmd = new SqlCommand(query, con);

            SqlDataReader dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                string scode = dr.GetString(dr.GetOrdinal("code"));
                comboBox2.Items.Add(scode);

            }
        }
        catch (Exception ex)
        {

            MessageBox.Show(ex.ToString());
        }
    }

这是现在考虑后台工作人员的样子:

This is how it looks now taking into consideration background worker:

 private List <string> items;
    void fillLiguanea()
    {
        items = new List<string>();
        this.liguanea_Lane2TableAdapter.Fill(this.pharmaciesDataSet3.Liguanea_Lane2);
        try
        {

            string connectionString = "Data Source=LPMSW09000012JD\\SQLEXPRESS;Initial Catalog=Pharmacies;Integrated Security=True";
            SqlConnection con = new SqlConnection(connectionString);
            con.Open();
            string query = "SELECT * FROM dbo.Liguanea_Lane2";
            SqlCommand cmd = new SqlCommand(query, con);

            SqlDataReader dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                string scode = dr.GetString(dr.GetOrdinal("code"));
                // comboBox2.Items.Add(scode);
                items.Add(scode);
            }
        }
        catch (Exception ex)
        {

            MessageBox.Show(ex.ToString());
        }
    }

下面是我的后台工作器函数,已对其进行了编辑,以填充有问题的comboBox,即comboBox2. 这是我的地勤工人:

Below are my background worker functions which have been edited to populate the comboBox in question, which is comboBox2. This is my back ground worker:

     private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        fillLiguanea();
    }

这是我的RunWorkerCOmpleted:

This is my RunWorkerCOmpleted:

  private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {

        if (comboBox4.SelectedIndex == 0)
        {


            foreach (var item in items)
            {
                comboBox2.Items.Add(item);
            }
        }
    }

我的问题是我要去哪里错了?代码应该做的是基于对combox4索引的选择从我的数据库中填充comboBox2.目前没有任何反应.我要去哪里错了?

My question is where am I going wrong? what the code should do is populate comboBox2 from my database based on the selection of combox4's index. Currently nothing happens. Where am I going wrong?

推荐答案

使用BackgroundWorker时,您可以考虑以下模式:

When using BackgroundWorker you can consider such pattern:

  1. 处理DoWork事件并在那里调用耗时的任务.
    请记住,该事件是在与UI线程不同的另一个线程中引发的,因此,如果出于任何原因要在事件中执行一些UI代码,则应使用Invoke进行线程安全调用到UI元素.
    将耗时的UI任务放在DoWork中是没有用的.因为该任务应使用Invoke在UI线程中运行,这将使UI线程再次变得繁忙.

  1. Handle DoWork event and call the time-consuming task there.
    Keep in mind the event is raised in another thread different than UI thread, so if for any reason you want to do some UI code in the event you should use Invoke to make a thread safe call to a UI element.
    Putting time-consuming UI tasks in the DoWork is useless. Because the task should be run in UI thread using Invoke and it will make the UI thread busy again.

您可以处理RunWorkerCompleted事件,以在DoWork中的工作完成后执行一些任务.例如,在DoWork中加载数据后,可以使用在RunWorkerCompleted中加载的数据填充ComboBox.

You can handle RunWorkerCompleted event to perform some tasks after the work in DoWork got completed. For example after you load data in DoWork, you can use the loaded data in RunWorkerCompleted to fill a ComboBox.

您应该调用组件的RunWorkerAsync方法以开始处理DoWork事件.
○当异步任务正在使用该组件的实例运行时,您无法使用同一组件启动另一个任务,因此,为防止异常,应检查this.backgroundWorker1.IsBusy,如果该组件不忙,请调用该方法.

You should call RunWorkerAsync method of the component to start processing DoWork event.
○ When an async task is running using an instance of the component you can not start another task using the same component, so to prevent exception you should check this.backgroundWorker1.IsBusy and if the component is not busy call the method.

该组件很好地支持错误报告,进度更改或取消执行.要了解有关这些功能的更多信息,请查看

The component has a good support for error reporting or progress changing or cancelling the execution. To learn more about the features, take a look at documentations.

对于.NET 4.5及更高版本,您可以使用 async/等待模式以执行异步任务.

For .NET 4.5 and later, you can use async/await pattern to perform asynchronous tasks.

示例

我想您当前有一个LoadData方法:

I suppose you have a LoadData method currently:

public void LoadData()
{
    this.categoryTableAdapter.Fill(this.testDBDataSet.Category);
}

并且您想用使用LoadData加载的数据填充控件.因此,您可以像这样处理DoWorkRunWorkerCompleted:

And you want to populate a control with data which you load using LoadData. So you can handle the DoWork and RunWorkerCompleted like this:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    LoadData();
}

private void backgroundWorker1_RunWorkerCompleted(object sender, 
    RunWorkerCompletedEventArgs e)
{
    this.comboBox1.DataSource = this.testDBDataSet.Category;
    this.comboBox1.DisplayMember = "Name";
}

此外,当您要开始执行任务时,还应该调用RunWorkerAsync,例如:

Also you should call the RunWorkerAsync when you want the task get started, for example:

private void button1_Click(object sender, EventArgs e)
{
    if (!this.backgroundWorker1.IsBusy)
        this.backgroundWorker1.RunWorkerAsync();
}

这篇关于后台工作者尝试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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