貌似被我琢磨出来结果了
DoWork里面
string[] st = e.Argument as string[];ProgressChanged里面
ListViewItem lv = e.UserState as ListViewItem;

解决方案 »

  1.   

    BackgroundWorker 应该很少有需要传递参数的时候。因为当它工作的时候,所有的条件都已经准备好了。
      

  2.   

    Q我遇到了一个问题,是在进度事件及结束事件,不是在DoWork事件中,在调试的时候全弹出说线程外建立的控件错误,但不是调试的情况直接运行生成的程序就不会有这错误,这是什么原因
      

  3.   


     private void searchKey_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
      this.Invoke(new MethodInvoke(()=>{            this.listView.Items.Add();这里面我想加载到ListView控件里*/
          }));        }
    这样才行的要用委托,BackgroundWorker 的ProcessChanged事件是由子线程抛出的,不像DoWork他从UI线程转了一手。
      

  4.   

    我之前在ProcessChanged事件和RunWorkerCompleted事件中都是直接操作窗体控件也没有问题,只是在DoWork事件中要用委托,好像跟你说的不太一样。不知道是不是因为这一次的BackgroudWorker是因为由fileSystemWatcher_Changed事件启动的原因?
      

  5.   

    fileSystemWatcher_Changed 这个肯定要委托的。
    好像这个ProcessChanged 这个也要用上委托的,不知是不是我记错了。,其他的RunWorkerCompleted这个内部有做了处理通过UI线程中转所以不用委托。
      

  6.   

    ProcessChanged这个应该是不需要的,因为我之前操作进度条及加载到ListView时都不会报错。不知道这次为什么会调试的时候报错,但运行的时候不会报错。
      

  7.   

    我试了ProcessChanged 这个没问题 ,fileSystemWatcher_Changed 绝对要委托的。运行不报错可能你有设允许夸线程调用控件了,
      

  8.   

    我在fileSystemWatcher_Changed里面是用了委托的,调试会有错误,而且错误出现在ProcessChanged,但运行没有错误,我就是很奇怪
      

  9.   

            private void fileSystemWatcher_Changed(object sender, FileSystemEventArgs e)
            {
                if (this.backgroundWorker.IsBusy != true)
                {
                    this.Invoke((MethodInvoker)delegate
                    {
                        this.listView.Enabled = false;
                        this.listView.Items.Clear();
                        this.listView.BeginUpdate();
                        this.AddItem.Visible = false;
                        this.progressBar1.Visible = true;
                    });
                    this.backgroundWorker.RunWorkerAsync();
                }
            }
            private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
            {
                OleDbConnection timeCon = new OleDbConnection(tCon);
                OleDbConnection dataCon = new OleDbConnection(con);
                try
                {
                    string tSql = @"select * from [新油缸目录-Time] where";
                    string dt = "2012-12-12";
                    if (Program.userGroup == "工程部")
                    {
                        if (Program.userPost == "部门主管" || Program.userPost == "部门经理")
                            tSql = tSql + " FinishTime =#" + dt + "#";
                        else if (Program.userPost == "部门职员")
                        {
                            tSql = tSql + @" Design ='无'";
                            tSql = tSql + @" or (Design='" + Program.userName + "' and Proofread='无')";
                            tSql = tSql + @" or (Design='" + Program.userName + "' and Proofread<>'无' and JDE='无')";
                            tSql = tSql + @" or (Proofread='" + Program.userName + "' and Crafts ='无')";
                        }
                    }
                    else if (Program.userGroup == "制造部")
                    {
                        if (Program.userPost == "部门主管" || Program.userPost == "部门经理")
                            tSql = tSql + " FinishTime =#" + dt + "#";
                        else
                            tSql = tSql + " Crafts=='" + Program.userName + "' and Audit ='无'";
                    }
                    else return;
                    if (timeCon.State == ConnectionState.Closed) timeCon.Open();
                    if (dataCon.State == ConnectionState.Closed) dataCon.Open();
                    OleDbCommand timeCmd = new OleDbCommand(tSql, timeCon);
                    OleDbDataReader timeRead = timeCmd.ExecuteReader();
                    while (timeRead.Read())
                    {
                        string _sn = timeRead["SN"].ToString();
                        string _item = timeRead["Item"].ToString();
                        string _classification = timeRead["Classification"].ToString();
                        string _description = string.Empty;
                        string sql = @"select SN,Description from [新油缸目录] where SN='" + _sn + "'";
                        OleDbCommand dataCmd = new OleDbCommand(sql, dataCon);
                        OleDbDataReader dataRead = dataCmd.ExecuteReader();
                        if (dataRead.Read())
                        {
                            _description = dataRead["Description"].ToString();
                        } 
                        dataRead.Close();
                        dataCmd.Dispose();
                        string _design = timeRead["Design"].ToString();
                        string _proofread = timeRead["Proofread"].ToString();
                        string _crafts = timeRead["Crafts"].ToString();
                        string _audit = timeRead["Audit"].ToString();
                        string _jde = timeRead["JDE"].ToString();
                        string _finishTime = DateTime.Parse(timeRead["FinishTime"].ToString()).ToString("yyyy-MM-dd");
                        string _totalTime = timeRead["TotalTime"].ToString();
                        ListViewItem lv = new ListViewItem();                    if (_design == "无")/*新的Item*/
                        {
                            lv = new ListViewItem(new string[] { _sn, _item, "", _description }, null, NewItem);
                        }
                        else if (_design != "无" && _proofread == "无")/*已分配设计任务*/
                        {
                            lv = new ListViewItem(new string[] { _sn, _item, _design, _description }, null, Design);
                        }
                        else if (_jde != "" && _crafts == "无")/*待输入JDE系统*/
                        {
                            lv = new ListViewItem(new string[] { _sn, _item, _design, _description }, null, JDE);
                        }
                        else if (_proofread != "无" && _crafts == "无")/*已分配校对任务*/
                        {
                            lv = new ListViewItem(new string[] { _sn, _item, _proofread, _description }, null, Proofread);
                        }
                        else if (_crafts != "无" && _audit == "无")/*已分配工艺检查*/
                        {
                            lv = new ListViewItem(new string[] { _sn, _item, _crafts, _description }, null, Crafts);
                        }
                        else if (_audit != "无" && _finishTime == "2012-12-12")/*已分配审核任务*/
                        {
                            lv = new ListViewItem(new string[] { _sn, _item, _audit, _description }, null, Audit);
                        }                    if (_classification == "拉杆缸") lv.ForeColor = System.Drawing.Color.Green;
                        else if (_classification == "冶金缸") lv.ForeColor = System.Drawing.Color.OrangeRed;
                        else if (_classification == "方缸") lv.ForeColor = System.Drawing.Color.DeepPink;
                        else if (_classification == "外协缸") lv.ForeColor = System.Drawing.Color.Blue;
                        else if (_classification == "密封包") lv.ForeColor = System.Drawing.Color.SaddleBrown;
                        else if (_classification.IndexOf("cancel") > -1) lv.ForeColor = System.Drawing.Color.Red;
                        this.backgroundWorker.ReportProgress(1, lv);
                    }
                    timeRead.Close();
                    timeCmd.Dispose();
                }
                finally
                {
                    if (dataCon.State == ConnectionState.Open) dataCon.Close();
                    if (timeCon.State == ConnectionState.Open) timeCon.Close();
                }
            }        private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
            {
                ListViewItem lv = e.UserState as ListViewItem;
                this.listView.Items.Add(lv);
                this.progressBar1.Value = e.ProgressPercentage;
            }        private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
            {
                this.progressBar1.Visible = false;
                this.listView.EndUpdate();
                this.listView.Enabled = true;
                this.AddItem.Visible = true;
            }我现学现用的,很多代码可能对你们来说不要笑话我,但可以指点我,谢谢
      

  10.   


    大概要调这几部份
     if (this.backgroundWorker.IsBusy != true)
                {
                    this.Invoke((MethodInvoker)delegate
                    {
                        this.listView.Enabled = false;
                        this.listView.Items.Clear();
                        this.listView.BeginUpdate();
                        this.AddItem.Visible = false;
                        this.progressBar1.Visible = true;
                       this.backgroundWorker.RunWorkerAsync(); 〈=====这里放到委托里面
                    });
                    
                }
     ListViewItem lv = new ListViewItem();
     不要放到DoWord里面去实列 Doword只做数据处理不用管控件的建立,把处理后的数据封装到一个实体类中再通过backgroundWorker_ProgressChanged 去实例ListViewItem 
    如果你不想改动那就直接把 this.listView.Items.Add(lv); 这句移到 this.backgroundWorker.ReportProgress(1, lv);这的前面就可以了,然后
    this.backgroundWorker.ReportProgress(1, null);<--还有你前面的参数怎么都是1,应是个变量吧。变成这样
    this.listView.Items.Add(lv);
    this.backgroundWorker.ReportProgress(这里是进度变量, nul);
    好了睡觉
      

  11.   

    你在DoWork里面对控件操作了吧:
    lv.ForeColor = System.Drawing.Color.OrangeRed;
      

  12.   

    知道你的原因了你在这里创建了ListViewItem 还有楼上说的你又调用了  lv.ForeColor = System.Drawing.Color.Green;
      private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
      {
       ListViewItem lv = new ListViewItem(); 这相当于一个控件
        lv.ForeColor = System.Drawing.Color.Green;//这也是要委托的
    }
    还是把这两地方都放到ProcessChanges里才行
      

  13.   

    知道你的原因了你在这里创建了ListViewItem 还有楼上说的你又调用了  lv.ForeColor = System.Drawing.Color.Green;
      private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
      {
       ListViewItem lv = new ListViewItem(); 这相当于一个控件
        lv.ForeColor = System.Drawing.Color.Green;//这也是要委托的
    }
    还是把这两地方都放到ProcessChanges里才行这个不是在线程外创建的吧,会有影响吗?我在其他的窗体也有这样使用,调试的时候没有出错。按照你的意思,如果要移到ProcessChanges里面,是不是把所有的值都保存到一个List里面传过来再在ProcessChanges里面判断完?
      

  14.   

    知道你的原因了你在这里创建了ListViewItem 还有楼上说的你又调用了  lv.ForeColor = System.Drawing.Color.Green;
      private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
      {
       ListViewItem lv = new ListViewItem(); 这相当于一个控件
        lv.ForeColor = System.Drawing.Color.Green;//这也是要委托的
    }
    还是把这两地方都放到ProcessChanges里才行这个不是在线程外创建的吧,会有影响吗?我在其他的窗体也有这样使用,调试的时候没有出错。按照你的意思,如果要移到ProcessChanges里面,是不是把所有的值都保存到一个List里面传过来再在ProcessChanges里面判断完?DoWork是子线程跑的,这可以肯定的,所以只能放到DoWork外面去要移动ProceessChanges里
      

  15.   

    lv 是由DoWork创建的也不行吗?如果DoWork的工作只是查询数据库,而一大堆的判断都在ProceessChanges里做?
      

  16.   

    要记住所有的控件最好不要放到线程里去创建,线程里调控件必需用委托实现。DoWork的工作只做与UI介面无关的事,判断可以,只要不操作控件UI就可以。
      

  17.   

    要记住所有的控件最好不要放到线程里去创建,线程里调控件必需用委托实现。DoWork的工作只做与UI介面无关的事,判断可以,只要不操作控件UI就可以。那我这个ListView分组的应该怎么写?
    帮个忙写一下可以吗?
      

  18.   

    要记住所有的控件最好不要放到线程里去创建,线程里调控件必需用委托实现。DoWork的工作只做与UI介面无关的事,判断可以,只要不操作控件UI就可以。那我这个ListView分组的应该怎么写?
    帮个忙写一下可以吗?这样该明白了吧
     private void fileSystemWatcher_Changed(object sender, FileSystemEventArgs e)
            {
                if (this.backgroundWorker.IsBusy != true)
                {
                    this.Invoke((MethodInvoker)delegate
                    {
                        this.listView.Enabled = false;
                        this.listView.Items.Clear();
                        this.listView.BeginUpdate();
                        this.AddItem.Visible = false;
                        this.progressBar1.Visible = true;
                    });
                    this.backgroundWorker.RunWorkerAsync();
                }
            } private class ResultInfo
            {            public string _sn;
                public string _item;
                public string _classification;
                public string _description;            public string _design;
                public string _proofread;
                public string _crafts ;
                public string _audit;
                public string _jde;
                public string _finishTime;
                public string _totalTime;
            }
            private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
            {
                OleDbConnection timeCon = new OleDbConnection(tCon);
                OleDbConnection dataCon = new OleDbConnection(con);
                try
                {
                    string tSql = @"select * from [新油缸目录-Time] where";
                    string dt = "2012-12-12";
                    if (Program.userGroup == "工程部")
                    {
                        if (Program.userPost == "部门主管" || Program.userPost == "部门经理")
                            tSql = tSql + " FinishTime =#" + dt + "#";
                        else if (Program.userPost == "部门职员")
                        {
                            tSql = tSql + @" Design ='无'";
                            tSql = tSql + @" or (Design='" + Program.userName + "' and Proofread='无')";
                            tSql = tSql + @" or (Design='" + Program.userName + "' and Proofread<>'无' and JDE='无')";
                            tSql = tSql + @" or (Proofread='" + Program.userName + "' and Crafts ='无')";
                        }
                    }
                    else if (Program.userGroup == "制造部")
                    {
                        if (Program.userPost == "部门主管" || Program.userPost == "部门经理")
                            tSql = tSql + " FinishTime =#" + dt + "#";
                        else
                            tSql = tSql + " Crafts=='" + Program.userName + "' and Audit ='无'";
                    }
                    else return;
                    if (timeCon.State == ConnectionState.Closed) timeCon.Open();
                    if (dataCon.State == ConnectionState.Closed) dataCon.Open();
                    OleDbCommand timeCmd = new OleDbCommand(tSql, timeCon);
                    OleDbDataReader timeRead = timeCmd.ExecuteReader();                int index = 0;
                    while (timeRead.Read())
                    {
                        string _sn = timeRead["SN"].ToString();
                        string _item = timeRead["Item"].ToString();
                        string _classification = timeRead["Classification"].ToString();
                        string _description = string.Empty;
                        string sql = @"select SN,Description from [新油缸目录] where SN='" + _sn + "'";
                        OleDbCommand dataCmd = new OleDbCommand(sql, dataCon);
                        OleDbDataReader dataRead = dataCmd.ExecuteReader();
                        if (dataRead.Read())
                        {
                            _description = dataRead["Description"].ToString();
                        }
                        dataRead.Close();
                        dataCmd.Dispose();
                        string _design = timeRead["Design"].ToString();
                        string _proofread = timeRead["Proofread"].ToString();
                        string _crafts = timeRead["Crafts"].ToString();
                        string _audit = timeRead["Audit"].ToString();
                        string _jde = timeRead["JDE"].ToString();
                        string _finishTime = DateTime.Parse(timeRead["FinishTime"].ToString()).ToString("yyyy-MM-dd");
                        string _totalTime = timeRead["TotalTime"].ToString();                    ResultInfo info = new ResultInfo();
                        info._sn = _sn;
                        info._item = _item;
                        info._classification = _classification;
                        info._description = _description;                    info._design = _design;
                        info._proofread = _proofread;
                        info._crafts = _crafts;
                        info._audit = _audit;
                        info._jde = _jde;
                        info._finishTime = _finishTime;
                        info._totalTime = _totalTime;
                        index++;
                        this.backgroundWorker.ReportProgress(index, info);
                    }
                    timeRead.Close();
                    timeCmd.Dispose();
                }
                finally
                {
                    if (dataCon.State == ConnectionState.Open) dataCon.Close();
                    if (timeCon.State == ConnectionState.Open) timeCon.Close();
                }
            }        private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
            {            ResultInfo info = e.UserState as ResultInfo;            ListViewItem lv = new ListViewItem();            if (info._design == "无")/*新的Item*/
                {
                    lv = new ListViewItem(new string[] { info._sn, info._item, "", info._description }, null, NewItem);
                }
                else if (info._design != "无" && info._proofread == "无")/*已分配设计任务*/
                {
                    lv = new ListViewItem(new string[] { info._sn, info._item, info._design, info._description }, null, Design);
                }
                else if (info._jde != "" && info._crafts == "无")/*待输入JDE系统*/
                {
                    lv = new ListViewItem(new string[] { info._sn, info._item, info._design, info._description }, null, JDE);
                }
                else if (info._proofread != "无" && info._crafts == "无")/*已分配校对任务*/
                {
                    lv = new ListViewItem(new string[] { info._sn, info._item, info._proofread, info._description }, null, Proofread);
                }
                else if (info._crafts != "无" && info._audit == "无")/*已分配工艺检查*/
                {
                    lv = new ListViewItem(new string[] { info._sn, info._item, info._crafts, info._description }, null, Crafts);
                }
                else if (info._audit != "无" && info._finishTime == "2012-12-12")/*已分配审核任务*/
                {
                    lv = new ListViewItem(new string[] { info._sn, info._item, info._audit, info._description }, null, Audit);
                }            if (info._classification == "拉杆缸") lv.ForeColor = System.Drawing.Color.Green;
                else if (info._classification == "冶金缸") lv.ForeColor = System.Drawing.Color.OrangeRed;
                else if (info._classification == "方缸") lv.ForeColor = System.Drawing.Color.DeepPink;
                else if (info._classification == "外协缸") lv.ForeColor = System.Drawing.Color.Blue;
                else if (info._classification == "密封包") lv.ForeColor = System.Drawing.Color.SaddleBrown;
                else if (info._classification.IndexOf("cancel") > -1) lv.ForeColor = System.Drawing.Color.Red;
                this.listView.Items.Add(lv);
                this.progressBar1.Value = e.ProgressPercentage;
            }
      

  19.   

    想知道最大值,那改用DataSet取值,不要用DataReader这样就能知道你取到的最大记录数了。然后用for(int i=0 ;i<table.Row.Count i++) 处理把那个i传进去就是了