如何使用多线程更新datagridview

时间:2017-07-18 17:18:20

标签: c# multithreading winforms datagridview

我是这个多线程概念的新手,并花了很多时间做我的RnD,但却无法完成任务。我尝试做的与交易应用程序类似。我在Windows窗体中有一个datagridview,显示来自sql数据库的多条记录。它有4列(十进制值)。我还有每分钟更新的txt文件。我必须从txt文件中读取最新行,并将此行的十进制值与datagridview中的每个十进制列进行比较。基于这种比较,我试图改变gridview单元格的颜色。我发现我的代码在逻辑上是正确的,但不知何故它无法正常工作。对于网格中的每一行,一个线程应该启动,但只启动一个线程,用于网格中的最后一个记录。我附加了我的代码。请帮我解决这个问题。 ** InitiateAlert ::它应循环遍历网格并为每条记录启动一个新线程。

checkiftargetreached ::每个Thread应该使用参数调用此函数。这里十进制值的比较是doen和网格单元格颜色设置。**

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace MultithredingSample
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
        }

        private void btnshow_Click(object sender, EventArgs e)
        {
            DataSet ds = new DataSet();

            DataTable dt = new DataTable("MyTable");
            dt.Columns.Add(new DataColumn("id", typeof(int)));
            dt.Columns.Add(new DataColumn("Val1", typeof(decimal)));
            dt.Columns.Add(new DataColumn("Val2", typeof(decimal)));
            dt.Columns.Add(new DataColumn("Val3", typeof(decimal)));
            dt.Columns.Add(new DataColumn("Flag", typeof(Boolean)));

            DataRow dr = dt.NewRow();
            dr["id"] = 1;
            dr["Val1"] = 23104.10;
            dr["Val2"] = 23154.10;
            dr["Val3"] = 23845.45;
            dr["Flag"] = true;
            dt.Rows.Add(dr);


            dr = dt.NewRow();
            dr["id"] = 2;
            dr["Val1"] = 25104.10;
            dr["Val2"] = 25154.10;
            dr["Val3"] = 25845.45;
            dr["Flag"] = true;
            dt.Rows.Add(dr);



            dataGridView1.DataSource = dt;


        }


private void checkiftargetreached(Int32 rowid,decimal val1,decimal val2, decimal val3, string filepath)
{
string line;
try
   {

   while (Convert.ToInt16(this.dataGridView1.Rows[rowid].Cells["Flag"].Value) == 1)
   {

    FileStream fs = new FileStream("C:\\Users\\username\\Downloads\\" + filepath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
    StreamReader sr = new StreamReader(fs);
    DataTable dtrec = new DataTable();
    line = sr.ReadLine();
    string[] values = line.Split(',');
    for (int i = 0; i <= values.Length - 1; i++)
    {dtrec.Columns.Add(values[i]);}

  line = sr.ReadLine();
  DataRow dr = dtrec.NewRow();
  string[] values2 = line.Split(',');
  for (int i = 0; i <= values2.Length - 1; i++)
  {dr[i] = values2[i];}
  dtrec.Rows.Add(dr);
  if(Convert.ToDecimal(dtrec.Rows[0][1]) == Convert.ToDecimal(this.dataGridView1.Rows[rowid].Cells["Val1"].Value))
    {
     if (this.dataGridView1.InvokeRequired){
this.dataGridView1.BeginInvoke((MethodInvoker)delegate () { this.dataGridView1.Rows[rowid].Cells["Val1"].Style.BackColor = Color.Aqua; });
                        }

                    }
  else if (Convert.ToDecimal(dtrec.Rows[0][1]) == Convert.ToDecimal(this.dataGridView1.Rows[rowid].Cells["Val2"].Value))
                    {
                        if (this.dataGridView1.InvokeRequired)
                        {
                            this.dataGridView1.BeginInvoke((MethodInvoker)delegate () { this.dataGridView1.Rows[rowid].Cells["Val2"].Style.BackColor = Color.Aqua; this.dataGridView1.Rows[rowid].Cells["Flag"].Value = 0; });
                        }

                    }
                    else if (Convert.ToDecimal(dtrec.Rows[0][1]) == Convert.ToDecimal(this.dataGridView1.Rows[rowid].Cells["Val3"].Value))
                    {

                        if (this.dataGridView1.InvokeRequired)
                        {
                            this.dataGridView1.BeginInvoke((MethodInvoker)delegate () { this.dataGridView1.Rows[rowid].Cells["Val3"].Style.BackColor = Color.Aqua; });

                        }

                    }
                    else
                    {

                        if (this.dataGridView1.InvokeRequired)
                        {
                            this.dataGridView1.BeginInvoke((MethodInvoker)delegate () { this.dataGridView1.Rows[rowid].Cells["Val3"].Style.BackColor = Color.IndianRed; });
                        }
                    }



                }


            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void InitiateAlerts()
        {
            Int32 row;
            decimal val1, val2, val3;

            try
            {
                for (int j = 0; j <= dataGridView1.Rows.Count - 1; j++)
                {

                    if (this.dataGridView1.InvokeRequired)
                    {
                        this.dataGridView1.BeginInvoke((MethodInvoker)delegate ()
                        {


                            if (Convert.ToInt16(this.dataGridView1.Rows[j].Cells["Flag"].Value) == 1)
                            {

                                row = j;
                                val1 = Convert.ToDecimal(this.dataGridView1.Rows[row].Cells["Val1"].Value);
                                val2 = Convert.ToDecimal(this.dataGridView1.Rows[row].Cells["Val2"].Value);
                                val3 = Convert.ToDecimal(this.dataGridView1.Rows[row].Cells["Val3"].Value);

                                Thread TH = new Thread(() => checkiftargetreached(row, val1, val2, val3, "A" + row.ToString() + ".txt"));
                                TH.Name = "A" + row.ToString() + ".csv";
                                TH.Start();
                            }

                        });


                    }
                    else
                    {

                        if (Convert.ToInt16(this.dataGridView1.Rows[j].Cells["Flag"].Value) == 1)
                        {

                            row = j;
                            val1 = Convert.ToDecimal(this.dataGridView1.Rows[row].Cells["Val1"].Value);
                            val2 = Convert.ToDecimal(this.dataGridView1.Rows[row].Cells["Val2"].Value);
                            val3 = Convert.ToDecimal(this.dataGridView1.Rows[row].Cells["Val3"].Value);

                            Thread TH = new Thread(() => checkiftargetreached(row, val1, val2, val3, "A" + row.ToString() + ".txt"));
                            TH.Name = "A" + row.ToString() + ".csv";
                            TH.Start();
                        }

                    }

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }


        }

        private void btnthread_Click(object sender, EventArgs e)
        {
            InitiateAlerts();
        }
    }
}

1 个答案:

答案 0 :(得分:0)