BackgroundWorker无法正常工作

BackgroundWorker无法正常工作

本文介绍了C#BackgroundWorker无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试让BackgroundWorker正常工作.当您单击查看订单"按钮时,它将在正在检索新订单..."等行中显示一条消息,并会进行后台工作(mysql查询),现在,DoWork方法中有很多东西,并且没有任何事情完成.

I'm trying to get this BackgroundWorker to work. When you click the View Orders button, it will display a message along the lines of "Retrieving new orders..." etc, and will do background work (mysql query), now, there's a bunch of stuff inside the DoWork method, and none of it gets done.

我知道这不是因为MySQL查询,因为它不需要后台工作程序就可以正常工作.

I know it's not because of the MySQL Query because it works fine on its own without the background worker.

代码如下:

private void ViewOrders_Click(object sender, EventArgs e)
        {
            SlideTimer.Enabled = true;
            Alert("Retrieving unconfirmed orders. Please wait.",
                "Cancel",
                Information,
                true,
                Color.FromArgb(63, 187, 249)
            );
            action = Action.ViewOrder;

            bWorker.WorkerSupportsCancellation = true;
            bWorker.DoWork += new DoWorkEventHandler(bWorker_DoWork);
            bWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bWorker_RunWorkerCompleted);

            bWorker.RunWorkerAsync();
        }

        void bWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            SlideTimer.Enabled = true;
            Alert("All unconfirmed orders have been retrieved.",
                "Dismiss",
                Information,
                true,
                Color.FromArgb(63, 187, 249)
            );
            action = Action.None;
        }

        void bWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            // Connect to Database, check for orders, and end.
            if (bWorker.CancellationPending == true)
            {
                e.Cancel = true;
            }
            else
            {
                if (action == Action.ViewOrder)
                {
                    thelist.Clear();
                    thelist.Visible = true;
                    thelist.BringToFront();
                    MessageBox.Show("");
                    thelist.Columns.Add("Order #");
                    thelist.Columns.Add("Name");
                    thelist.Columns.Add("E-mail Address");
                    thelist.Columns.Add("Delivery Address");
                    thelist.Columns.Add("Company");
                    thelist.Columns.Add("Phone Number");

                    // Check for new orders.
                    MySql.Data.MySqlClient.MySqlConnection msc = new MySql.Data.MySqlClient.MySqlConnection(cs);
                    try
                    {
                        msc.Open();

                        // Check for orders now.
                        string st = "SELECT DISTINCT(sessionid), firstname, lastname, email, streetaddress, suburb, postcode, state, company, phone FROM mysql_9269_dbase.order";
                        MySql.Data.MySqlClient.MySqlCommand cd = new MySql.Data.MySqlClient.MySqlCommand(st, msc);
                        MySql.Data.MySqlClient.MySqlDataReader msdr = cd.ExecuteReader();

                        while (msdr.Read())
                        {
                            if (thelist.Items.Count == 0)
                            {
                                ListViewItem LItem = new ListViewItem(msdr[0].ToString());
                                ListViewItem.ListViewSubItemCollection SubItems = new ListViewItem.ListViewSubItemCollection(LItem);

                                SubItems.Add(msdr[1].ToString() + " " + msdr[2].ToString());
                                SubItems.Add(msdr[3].ToString());
                                SubItems.Add(msdr[4].ToString() + " " + msdr[5].ToString() + " " + msdr[6].ToString() + " " + msdr[7]);
                                SubItems.Add(msdr[8].ToString());
                                SubItems.Add(msdr[9].ToString());

                                thelist.Items.Add(LItem);

                                thelist.Update();
                            }
                            else
                            {
                                sound.Play();

                                //status.Text = "Records found; Retrieving now.";
                                var found = false;

                                foreach (var item in thelist.Items)
                                {
                                    if (item.ToString().Contains(msdr[0].ToString()))
                                        found = true;
                                }
                                if (thelist.Items.Count == 0 || !found)
                                {
                                    ListViewItem LItem = new ListViewItem(msdr[0].ToString());
                                    ListViewItem.ListViewSubItemCollection SubItems = new ListViewItem.ListViewSubItemCollection(LItem);

                                    SubItems.Add(msdr[1].ToString() + " " + msdr[2].ToString());
                                    SubItems.Add(msdr[3].ToString());
                                    SubItems.Add(msdr[4].ToString() + " " + msdr[5].ToString() + " " + msdr[6].ToString() + " " + msdr[7]);
                                    SubItems.Add(msdr[8].ToString());
                                    SubItems.Add(msdr[9].ToString());

                                    thelist.Items.Add(LItem);

                                    thelist.Update();
                                }
                            }
                        }
                    }
                    catch (Exception en)
                    {
                        Alert(en.Message,
                            "Retry",
                            Error,
                            true,
                            Color.FromArgb(249, 87, 55)
                        );
                    }
                    msc.Close();

                }
                thelist.Visible = true;
                thelist.BringToFront();
            }
        }

        private void MessageLink_Click(object sender, EventArgs e)
        {
            switch (MessageLink.Text)
            {
                case "Cancel":
                    bWorker.CancelAsync();

                    SlideTimer.Enabled = true;
                    Alert("You have successfully cancelled the current operation.",
                        "Dismiss",
                        Information,
                        true,
                        Color.FromArgb(63, 187, 249)
                    );
                    action = Action.None;
                    break;
                case "":
                    break;
                default:
                    break;
            }
        }

没有错误或任何东西.只是什么都没有发生.是什么原因导致Background(所谓的)Worker不执行DoWork()?

There's no errors or anything. Just that Nothing happens. What's causing the Background(so called)Worker to not DoWork()?

*抱歉,冗长的代码片段.

*Sorry for the lengthy code snip.

推荐答案

您已经连接了回调,但实际上并未调用RunWorkerAsync来启动它.

You've hooked up the callbacks but not actually called RunWorkerAsync to start it going.

顺便说一句,您还将在DoWork方法中调用UI元素,这将失败.您需要使用BeginInvoke将更新混搭回UI线程,或在RunWorkerComplete方法(自动在UI线程上运行)中进行更新.

As an aside, you're also calling UI elements in the DoWork method which will fail. You need to use BeginInvoke to mashal the updates back to the UI thread or do the updates in the RunWorkerComplete method (which is run on the UI thread automatically).

这篇关于C#BackgroundWorker无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 05:33