Windows窗体嵌入式进度栏背景工人

时间:2017-09-12 06:09:07

标签: c# multithreading user-interface backgroundworker

我想在表单中使用进度条但遇到问题。

在表单加载时,进度条完成,列表视图填充了" connected"的图标。设备。

当我尝试在网络适配器列表中选择另一个索引时,进度条和列表视图会清除,但会抛出异常并且GUI中没有任何内容。

  

抛出异常:' System.InvalidOperationException'在System.Windows.Forms.dll

我认为这是一个线程问题,但我不知道。

以下是代码,非常感谢任何帮助或建议。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class ConnectDialog : Form
    {
        BackgroundWorker bkgndWorker = null;
        Dictionary<string, int> dictionary = new Dictionary<string, int>();
        ImageList deviceImageList = new ImageList();

        public ConnectDialog()
        {
            InitializeComponent();       
        }

        public ConnectDialog(List<String> ipAddr)
        {
            InitializeComponent();
            cboNetworkAdapter.Items.AddRange(ipAddr.ToArray());
            cboNetworkAdapter.SelectedIndex = 0;
        }

        private void ConnectDialog_Load(object sender, EventArgs e)
        {
            Bitmap devImage = Properties.Resources.devIcon;
            deviceImageList.Images.Add(devImage);
            deviceImageList.ImageSize = new Size(30, 30);
        }

        private void cboNetworkAdapter_SelectedIndexChanged(object sender, EventArgs e)
        {
            StartWorking();
        }

        private void StartWorking()
        {
            prgBarConnect.Value = 0;
            dictionary.Clear();
            lstvwDevIds.Clear();
            bkgndWorker = new BackgroundWorker();

            bkgndWorker.DoWork += new DoWorkEventHandler(bkgndWorker_DoWork);
            bkgndWorker.ProgressChanged += new ProgressChangedEventHandler(bkgndWorker_ProgressChanged);
            bkgndWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bkgndWorker_RunWorkerCompleted);
            bkgndWorker.WorkerReportsProgress = true;
            bkgndWorker.RunWorkerAsync();
            bkgndWorker.Dispose();
        }

        private void bkgndWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            int numDevs = 0;
            switch (cboNetworkAdapter.SelectedIndex)
            {
                case 0:
                    numDevs = 4;
                    break;
                case 1:
                    numDevs = 1;
                    break;
                case 2:
                    numDevs = 10;
                    break;
            }
            populateImages(numDevs);
        }

        void bkgndWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            prgBarConnect.Value = e.ProgressPercentage;
        }

        void bkgndWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            foreach (KeyValuePair<String, int> entry in dictionary)
            {
                ListViewItem lstViewDevImage = new ListViewItem(entry.Key, entry.Value);
                lstvwDevIds.Items.Add(lstViewDevImage);
            }

            if (lstvwDevIds.SelectedItems.Count > 0)
                Console.WriteLine(String.Format("Device id: {0}", lstvwDevIds.Items.IndexOf(lstvwDevIds.SelectedItems[0])));

            lstvwDevIds.LargeImageList = deviceImageList;
        }

        private void populateImages(int numDevs)
        {
            for (int i = 1; i <= numDevs; i++)
            {
                System.Threading.Thread.Sleep(100);
                int percents = (i * 100) / numDevs;

                String lstVwItemDesc = String.Format("Dev {0}", i - 1);
                dictionary.Add(lstVwItemDesc, deviceImageList.Images.Count - 1);
                bkgndWorker.ReportProgress(percents, i);
            }
        }
    }
}

Success on Form Load

1 个答案:

答案 0 :(得分:2)

请勿在要运行的BackGroundWorker上调用Dispose。这样做:

// if we have an instance of a backgroundworker ...
// Cancel and Dispose that one
if (bkgndWorker !=null) 
{
    // in case you want to end the DoWork nicely
    bkgndWorker.CancelAsync(); 
    bkgndWorker.Dispose();
}

// start again
bkgndWorker = new BackgroundWorker();

bkgndWorker.DoWork += new DoWorkEventHandler(bkgndWorker_DoWork);
bkgndWorker.ProgressChanged += new ProgressChangedEventHandler(bkgndWorker_ProgressChanged);
bkgndWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bkgndWorker_RunWorkerCompleted);
bkgndWorker.WorkerReportsProgress = true;
bkgndWorker.RunWorkerAsync();
// removed the call to Dispose

您可能还希望在表单上实现Dispose以对BackgroundWorker实例进行相同的清理。