C#BackgroundWorker 不工作

发布于 2024-10-23 01:01:20 字数 6489 浏览 4 评论 0原文

我正在尝试让这个BackgroundWorker 工作。当您单击“查看订单”按钮时,它将显示一条类似于“检索新订单...”等的消息,并将执行后台工作(mysql 查询),现在,DoWork 方法中有一堆东西,并且一切都没有完成。

我知道这不是因为 MySQL 查询,因为它无需后台工作人员即可自行正常工作。

这是代码:

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

没有错误或任何东西。只是什么也没发生。是什么导致后台(所谓的)Worker 不执行 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.

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

Here's the code:

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

心在旅行 2024-10-30 01:01:20

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

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

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

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

红ご颜醉 2024-10-30 01:01:20
MessageBox.Show("");

这会造成一个大问题。

您无法从非 UI 线程调用 UI。我很惊讶它没有引发异常。充其量它可能会导致您的线程中止并且不执行任何操作。

theList 看起来也像一个 UI 元素。如果您要添加控件,那么您需要通过事件将数据传递到 UI,以便您可以在那里更新它。

您还可以:

Alert(en.Message,
    "Retry",
    Error,
    true,
    Color.FromArgb(249, 87, 55)
);

在您的异常处理程序中。这看起来又像是您正在尝试调用 UI 元素。

MessageBox.Show("");

This will cause a big problem.

You can't call UI from a non UI thread. I'm surprised that it hasn't raised an exception. At best it's probably causing your thread to abort and not do anything.

The theList looks like a UI element as well. If you are adding to control then you need to pass the data via an event to the UI so you can update it there.

You also have:

Alert(en.Message,
    "Retry",
    Error,
    true,
    Color.FromArgb(249, 87, 55)
);

In your exception handler. Again this looks like you are trying to call UI elements.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文