Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
Hello!
 
I am a developer under training and i am working on a large project wich involves windows forms and sql server.
 
This program will be a personell planning system for a factory some day
<img src='http://bildr.no/thumb/1029350.jpeg' alt='1029350' />
I have some trouble with the code for my backgroundworker wich populates a datagridview.
 
1st run it takes 15-20ms trough 12 loops.
2nd run it takes 750ms for first loop, then 0-15ms for the rest
 
* I have checked there is no trouble with filling of datatables. The tableadapter.fill are done in the UI thread, and it is consistent of 10-20ms. The form is also set up tho make the backgrounworker.dowork on seperate user input.
 
so far i have found out that the datagridview.rows.add is the part which is holding the whole method back, it is running for 750ms on the 2. update cycle, on only the first new datagridview. It also behaves like this for the 3,4,5 and so one cycles, but only on the first datagridview. The first datagridview is always the one which is shown to the user.
The code disposes it if it exists a datagridview with the same name on the new update cycle. I have tried commenting out this with no difference to timespan (new update cycle)
 
foreach (Control c in this.tabControl1.TabPages[måned-1].Controls)
            {
                if (c.Name == "dgv" + måned)
                {
                    //this.tabControl1.Controls.Remove(c);
                    //c.Dispose();
                }
            }
 

 
form_load:
1. fill = 10ms
2. 12 runs with backgroundworker to create 12 new datagridview = 15-20ms each
 
btnUpdate_click:
1. fill = 10ms
2. 1 of 12 runs with backgroundworker to create 12 new datagridview = 690-800ms
3. 2 to 12 runs with backgroundworker to create 12 new datagridview = 0(!)-20ms

 

<pre lang="c#"><pre> DateTime dts = DateTime.Now;
            //Application.DoEvents();
            foreach (DataRowView drv in dvBrukere)
            {
                int nyRow = dgv.Rows.Add();
 
                dgv.Rows[nyRow].Cells[0].Value = drv["Avdeling"].ToString();
                dgv.Rows[nyRow].Cells[1].Value = drv["Avdeling arbeidsplan"].ToString();
                dgv.Rows[nyRow].Cells[2].Value = drv["Brukernavn"].ToString();
     
                AnsattFraDato = DateTime.Parse(drv["Ansatt fra dato"].ToString());
                GyldigTilDato = DateTime.Parse(drv["Gyldig til"].ToString());
                teller = 0;
                while (teller < dagerPrMåned)
                {
                    teller++;
                    TelleDatoTidlig = new DateTime(år, måned, teller, 0, 0, 0);
                    TelleDatoSen = new DateTime(år, måned, teller, 23, 59, 59);
                    if((TelleDatoSen.DayOfWeek != DayOfWeek.Saturday) && (TelleDatoSen.DayOfWeek !=DayOfWeek.Sunday))
                        if ((AnsattFraDato <= TelleDatoSen) && (GyldigTilDato >= TelleDatoTidlig))
                        {
                            dgv.Rows[nyRow].Cells[teller.ToString()].Value = "Jobb";
                            dgv.Rows[nyRow].Cells[teller.ToString()].Style.BackColor = Color.LightGreen;
                        }
                }
            }
            DateTime dtsto = DateTime.Now;
            TimeSpan ts1 = dtsto - dts;
            MessageBox.Show(ts1.Milliseconds.ToString());
 

 
which is takes from this:
 
<pre lang="c#"><pre>private void backGroundWorkerStart()
        {
            //Application.DoEvents();
            this.Cursor = Cursors.AppStarting;
            LåsSkjema(true);
            BackgroundWorker bgw = new BackgroundWorker();
            bgw.DoWork +=new DoWorkEventHandler(bgwDgvOppretter_DoWork);
            bgw.WorkerReportsProgress = true;
           
            bgw.ProgressChanged += new ProgressChangedEventHandler(bgw_ProgressChanged);
            bgw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgw_RunWorkerCompleted);
            bgw.RunWorkerAsync();
 
        }
        void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
                MessageBox.Show(e.Error.Message, "DoseStudio");
 
            this.Cursor = Cursors.Default;
            LåsSkjema(false);
            KjørerBGW = false;
            setSkjemaStatus("Sist oppdatert: " + DateTime.Now.ToString(), 100);
        }
 
        int step = 0;
        void bgw_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            step++;
            setSkjemaStatus("Oppdaterer bakgrunnsmåned " + step, e.ProgressPercentage);
            //Application.DoEvents();
        }
        private delegate void OppdaterEnMånedDataDelegate(object sender, int år, int måned);
        private void OppdaterEnMånedData(object sender, int år, int måned)
        {
            LåsSkjema(true);
            if (sender == null)
            { }
            else
            {
                if (sender.GetType().Equals(typeof(BackgroundWorker)))
                    this.Cursor = Cursors.AppStarting;
                else
                {
                    setSkjemaStatus("Oppdaterer denne måned", 50);
                    this.Cursor = Cursors.WaitCursor;
                }
            }
            DateTime dtStart = DateTime.Now;
            DateTime dtStopp;
            TimeSpan ts;
            
            string månedString =måned.ToString();
            if(månedString.Length==1)
                månedString=string.Format("00", måned);
            foreach (Control c in this.tabControl1.TabPages[måned-1].Controls)
            {
                if (c.Name == "dgv" + måned)
                {
                    //this.tabControl1.Controls.Remove(c);
                    //c.Dispose();
                }
            }
 
            AntallGangerKjørt++;
            //this.Controls["dgv" + måned].Dispose();
           
   
            DataGridView dgv = new DataGridView();
            typeof(DataGridView).InvokeMember("DoubleBuffered", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.SetProperty, null, dgv, new object[] { true }); 
            foreach (TabPage tp in tabControl1.TabPages)
            {
                if (Convert.ToInt32(tp.Name.Substring(tp.Name.Length - 2, 2)) == måned)
                {
                    tp.Controls.Add(dgv);
                }
            }
            dgv.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            dgv.Dock = System.Windows.Forms.DockStyle.Fill;
            dgv.Location = new System.Drawing.Point(0, 0);
            dgv.Name = Guid.NewGuid().ToString();//"dgv"+måned;
            dgv.Size = new System.Drawing.Size(964, 651);
            dgv.TabIndex = 0;
            _003_Util.dgwSetupHjelper dgws = new _003_Util.dgwSetupHjelper(dgv);
            dgws.filter = false;
            dgws.CopyPaste = true;
            dgws.settOppDGW();
            dgv.CellDoubleClick += new DataGridViewCellEventHandler(dgv_CellDoubleClick);
            
            dgv.Columns.Clear();
            dgv.Rows.Clear();
            
            dgv.Columns.Add("Avdeling","Avdeling");
            dgv.Columns.Add("Arbeidsplan","Arbeidsplan");
            dgv.Columns.Add("Brukernavn","Brukernavn");
            int customColumns = 3;
            int teller=0;
            int teller2;
            while (teller < customColumns)
            {
                dgv.Columns[teller].Frozen = true;
                dgv.Columns[teller].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                teller++;
            }
            
           int dagerPrMåned = DateTime.DaysInMonth(år, måned);
            DateTime dtsisteIMåneden = new DateTime(år, måned, dagerPrMåned, 23, 59, 59);
            DateTime dtFørsteIMåneden = new DateTime(år,måned, 1, 0, 0, 0);
            DateTime dtIdag = DateTime.Now;
            teller = 0;
            while(teller < dagerPrMåned)
            {
                teller++;
                dgv.Columns.Add(teller.ToString(), teller.ToString());
            }
            
            
            DateTime AnsattFraDato;
            DateTime GyldigTilDato;
            DateTime TelleDatoSen;
            DateTime TelleDatoTidlig;
            
            string rfilter = "";
            if(strAvdeling != "Alle")
                rfilter = "avdeling ='" + strAvdeling + "' and ";
            if ((strAvdeling == "Produksjon") && (strAvdelingArbeidsplan != "Alle"))
                rfilter = rfilter + " [Avdeling Arbeidsplan] ='" + strAvdelingArbeidsplan + "' and ";
 
            DataView dvBrukere = new DataView(dtTblBrukere);
            dvBrukere.RowFilter = rfilter + " [Ansatt fra dato]<='#" + dtsisteIMåneden.ToString() + "#' and [gyldig til]>='#" + dtFørsteIMåneden.ToString() + "#'";
            /*
            EnumerableRowCollection<DataRow> result;
            DataTable dtInternTblBrukere = dtTblBrukere;
            DataView dvBrukere = new DataView();
            
            if ((strAvdeling == "Alle") && (strAvdelingArbeidsplan == "Alle"))
            {
                result = from myrow in dtInternTblBrukere.AsEnumerable()
                         where myrow.Field<DateTime?>("Ansatt fra dato") <= dtsisteIMåneden
                         && myrow.Field<DateTime?>("Gyldig til") >= dtFørsteIMåneden
                         && myrow.Field<string>("Avdeling") != "Vikar"
                         //orderby myrow.Field<string>("Avdeling"), myrow.Field<string>("Avdeling arbeidsplan"), myrow.Field<string>("Brukernavn")
                         select myrow;
                dvBrukere = result.AsDataView();
            }
            else if ((strAvdeling != "Alle") && (strAvdelingArbeidsplan == "Alle"))
            {
                result = from myrow in dtInternTblBrukere.AsEnumerable()
                         where myrow.Field<DateTime?>("Ansatt fra dato") <= dtsisteIMåneden
                         && myrow.Field<DateTime?>("Gyldig til") >= dtFørsteIMåneden
                         && myrow.Field<string>("avdeling") == strAvdeling
                         orderby myrow.Field<string>("Avdeling"), myrow.Field<string>("Avdeling arbeidsplan"), myrow.Field<string>("Brukernavn")
                         select myrow;
                dvBrukere = result.AsDataView();
            }
            else if ((strAvdeling != "Alle") && (strAvdelingArbeidsplan != "Alle"))
            {
                result = from myrow in dtInternTblBrukere.AsEnumerable()
                         where myrow.Field<DateTime?>("Ansatt fra dato") <= dtsisteIMåneden
                         && myrow.Field<DateTime?>("Gyldig til") >= dtFørsteIMåneden
                         && myrow.Field<string>("avdeling") == strAvdeling
                         && myrow.Field<string>("Avdeling arbeidsplan") == strAvdelingArbeidsplan
                         orderby myrow.Field<string>("Avdeling"), myrow.Field<string>("Avdeling arbeidsplan"), myrow.Field<string>("Brukernavn")
                         select myrow;
                dvBrukere = result.AsDataView();
            }
            */
            DateTime dts = DateTime.Now;
            //Application.DoEvents();
            foreach (DataRowView drv in dvBrukere)
            {
                int nyRow = dgv.Rows.Add();
 
                dgv.Rows[nyRow].Cells[0].Value = drv["Avdeling"].ToString();
                dgv.Rows[nyRow].Cells[1].Value = drv["Avdeling arbeidsplan"].ToString();
                dgv.Rows[nyRow].Cells[2].Value = drv["Brukernavn"].ToString();
     
                AnsattFraDato = DateTime.Parse(drv["Ansatt fra dato"].ToString());
                GyldigTilDato = DateTime.Parse(drv["Gyldig til"].ToString());
                teller = 0;
                while (teller < dagerPrMåned)
                {
                    teller++;
                    TelleDatoTidlig = new DateTime(år, måned, teller, 0, 0, 0);
                    TelleDatoSen = new DateTime(år, måned, teller, 23, 59, 59);
                    if((TelleDatoSen.DayOfWeek != DayOfWeek.Saturday) && (TelleDatoSen.DayOfWeek !=DayOfWeek.Sunday))
                        if ((AnsattFraDato <= TelleDatoSen) && (GyldigTilDato >= TelleDatoTidlig))
                        {
                            dgv.Rows[nyRow].Cells[teller.ToString()].Value = "Jobb";
                            dgv.Rows[nyRow].Cells[teller.ToString()].Style.BackColor = Color.LightGreen;
                        }
                }
            }
            DateTime dtsto = DateTime.Now;
            TimeSpan ts1 = dtsto - dts;
            MessageBox.Show(ts1.Milliseconds.ToString());
           
            //Application.DoEvents();
            //Korrigerer og legger inn manuell arbeidsplan
            DateTime dtManuellFraDato;
            DateTime dtManuellTilDato;
            DataView dvManuellAPlan = new DataView(dtArbeidsPlanUtlån);
            dvManuellAPlan.RowFilter = "[Fra Dato]<='#" + dtsisteIMåneden.ToString() + "#' And [Til Dato] >='#" + dtFørsteIMåneden.ToString() + "#'";
            dvManuellAPlan.Sort = "Brukernavn";
            foreach (DataRowView drv in dvManuellAPlan)//kun korrigering av eksisterende oppføringer
            {
                dtManuellFraDato = DateTime.Parse(drv["Fra dato"].ToString());
                dtManuellTilDato = DateTime.Parse(drv["Til dato"].ToString());
 
                DataGridViewRow row = dgv.Rows
                    .Cast<DataGridViewRow>()
                    .Where(r => r.Cells["Brukernavn"].Value.ToString().Equals(drv["Brukernavn"].ToString()))
                    .FirstOrDefault();
                if (row != null)
                {
                    int index = row.Index;
                    if (dtManuellFraDato < dtFørsteIMåneden)
                        teller = 1;
                    else
                        teller = dtManuellFraDato.Day;
 
                    if (dtManuellTilDato > dtsisteIMåneden)
                        teller2 = dagerPrMåned;
                    else
                        teller2 = dtManuellTilDato.Day;
                    while (teller <= teller2)
                    {
                        TelleDatoSen = new DateTime(år, måned, teller, 0, 0, 0);
                        if ((TelleDatoSen.DayOfWeek != DayOfWeek.Saturday) && (TelleDatoSen.DayOfWeek != DayOfWeek.Sunday))
                        {
                            row.Cells[teller.ToString()].Style.BackColor = Color.Purple;
                            row.Cells[teller.ToString()].Value = "Utlånt";
                            row.Cells[teller.ToString()].ToolTipText = "Utlånt til " + drv["Avdeling"].ToString() + " " + Convert.ToDateTime(drv["Fra dato"].ToString()).ToShortDateString() + "-" + Convert.ToDateTime(drv["Til dato"].ToString()).ToShortDateString();
                        }
                        teller++;
                    }
                }
                
            }
 
            //Application.DoEvents();
            dvManuellAPlan.RowFilter =rfilter + dvManuellAPlan.RowFilter;
            foreach (DataRowView drv in dvManuellAPlan)//ny oppføring av manuell arbeidsplan
            {
                dtManuellFraDato = DateTime.Parse(drv["Fra dato"].ToString());
                dtManuellTilDato = DateTime.Parse(drv["Til dato"].ToString());
 
                string[] radString = new string[dagerPrMåned + 3];
                radString[0] = drv["Avdeling"].ToString();
                radString[1] = drv["Avdeling arbeidsplan"].ToString();
                radString[2] = drv["Brukernavn"].ToString();
                if(dtManuellFraDato<dtFørsteIMåneden)
                    teller = 1;
                else
                    teller = dtManuellFraDato.Day;
                if(dtManuellTilDato > dtsisteIMåneden)//tildato er i neste måned
                    teller2 = dagerPrMåned;
                else
                    teller2 = dtManuellTilDato.Day;
                while (teller <= teller2)
                {
                    TelleDatoSen = new DateTime(år, måned, teller, 0, 0, 0);
                    if ((TelleDatoSen.DayOfWeek != DayOfWeek.Saturday) && (TelleDatoSen.DayOfWeek != DayOfWeek.Sunday))
                        radString[teller+customColumns-1] = drv["Avdeling"].ToString();
                    teller++;
                }
                dgv.Rows.Add(radString);
                
            }
            //Application.DoEvents();
            DataView dvFerie = new DataView(dtFerieOversikt);
            dvFerie.RowFilter = "[Fra Dato]<='#" + dtsisteIMåneden.ToString() + "#' And [Til Dato] >='#" + dtFørsteIMåneden.ToString() + "#'";
            DateTime dtFerieFraDato;
            DateTime dtFerieTilDato;
            foreach (DataRowView drv in dvFerie)
            {
                dtFerieFraDato = DateTime.Parse(drv["Fra dato"].ToString());
                dtFerieTilDato = DateTime.Parse(drv["Til dato"].ToString());
 
                if (dtFerieFraDato < dtFørsteIMåneden)
                    teller = 1;
                else
                    teller = dtFerieFraDato.Day;
                if (dtFerieTilDato > dtsisteIMåneden)//tildato er i neste måned
                    teller2 = dagerPrMåned;
                else
                    teller2 = dtFerieTilDato.Day;
                string b;
                if (drv["brukernavn"].ToString().Equals("phuhly"))
                    b = drv["brukernavn"].ToString();
 
                DataGridViewRow row = dgv.Rows
                    .Cast<DataGridViewRow>()
                    .Where(r => r.Cells["Brukernavn"].Value.ToString().Equals(drv["Brukernavn"].ToString()))
                    .FirstOrDefault();
                if (row != null)
                {
                    while (teller <= teller2)
                    {
                        if (drv["Status"].ToString().ToLower() == "godkjent")
                        {
                            row.Cells[teller.ToString()].Style.BackColor = Color.Yellow;
                            row.Cells[teller.ToString()].Value = "Ferie";
                            row.Cells[teller.ToString()].ToolTipText = Convert.ToDateTime(drv["Fra dato"].ToString()).ToShortDateString() + "-" + Convert.ToDateTime(drv["Til Dato"].ToString()).ToShortDateString() + " - " + drv["Type"].ToString() + " - \n" + drv["Kommentar"].ToString();
                        }
                        else if (drv["Status"].ToString().ToLower() == "registrert")
                        {
                            row.Cells[teller.ToString()].Style.BackColor = Color.Orange;
                            row.Cells[teller.ToString()].Value = "Feriesøknad";
                            row.Cells[teller.ToString()].ToolTipText = Convert.ToDateTime(drv["Fra dato"].ToString()).ToShortDateString() + "-" + Convert.ToDateTime(drv["Til Dato"].ToString()).ToShortDateString() + " - " + drv["Type"].ToString() + " - \n" + drv["Kommentar"].ToString();
                        }
                        teller++;
                    }
                }
            }
 
            bool FremhevKolonne = false;
            
            if ((år == DateTime.Today.Year) && (måned == DateTime.Today.Month))
            {
                FremhevKolonne = true;
            }
            ///
            DataView dvHelligdager = new DataView(dtHelligdager);
            dvHelligdager.RowFilter = "[Dato] >= '#" + dtFørsteIMåneden.ToString() + "#' AND  [Dato] <= '#" + dtsisteIMåneden.ToString() + "#'";
            foreach(DataRowView drv in dvHelligdager)
            {
                teller = Convert.ToDateTime(drv["Dato"].ToString()).Day;
                foreach(DataGridViewRow dgvr in dgv.Rows)
                {
                    if (FremhevKolonne)
                    {
                        Font fnt = new Font(dgv.DefaultCellStyle.Font,FontStyle.Bold);
                        dgvr.Cells[DateTime.Today.Day.ToString()].Style.Font = fnt;
                    }
 
                    dgvr.Cells[teller.ToString()].Value = "";
                    dgvr.Cells[teller.ToString()].ToolTipText = drv["Tekst"].ToString();
                    dgvr.Cells[teller.ToString()].Style.BackColor = Color.FromArgb(255, 218, 122);
                }
            }
 
            DateTime dtArbeidsPlanDato;
            DataView dvArbeidsplan = new DataView(dtArbeidsplan);
            dvArbeidsplan.RowFilter = "[Dato] >= '#" + dtFørsteIMåneden.ToString() + "#' AND  [Dato] <= '#" + dtsisteIMåneden.ToString() + "#'";
            dvArbeidsplan.Sort = "dato desc, avdeling";
            foreach (DataRowView drv in dvArbeidsplan)
            {
                dtArbeidsPlanDato = DateTime.Parse(drv["Dato"].ToString());
                string c = drv["Brukernavn"].ToString();
          
                DataGridViewRow row = dgv.Rows
                    .Cast<DataGridViewRow>()
                    .Where(r => r.Cells["Brukernavn"].Value.ToString().Equals(drv["Brukernavn"].ToString()))
                    .FirstOrDefault();
                    //.First();
                if (row != null)
                {
                    if (drv["Funksjon"].ToString().ToLower().Contains("syk"))
                    {
                        row.Cells[dtArbeidsPlanDato.Day.ToString()].Value = "Syk";
                        row.Cells[dtArbeidsPlanDato.Day.ToString()].ToolTipText = "Fra arbeidsplan - " + drv["Funksjon"].ToString();
                        row.Cells[dtArbeidsPlanDato.Day.ToString()].Style.BackColor = Color.LightBlue;
                    }
                    if (drv["Funksjon"].ToString().ToLower().Contains("fri"))
                    {
                        row.Cells[dtArbeidsPlanDato.Day.ToString()].Value = "Fri";
                        row.Cells[dtArbeidsPlanDato.Day.ToString()].ToolTipText = "Fra arbeidsplan - " + drv["Funksjon"].ToString();
                        row.Cells[dtArbeidsPlanDato.Day.ToString()].Style.BackColor = Color.LightBlue;
                    }
                    if (row.Cells[dtArbeidsPlanDato.Day.ToString()].Value != null)
                    {
                        if ((drv["Funksjon"].ToString().ToLower().Contains("ferie")) && (row.Cells[dtArbeidsPlanDato.Day.ToString()].Value.ToString().ToLower() == "jobb"))
                        {
                            row.Cells[dtArbeidsPlanDato.Day.ToString()].Value = "Fri";
                            row.Cells[dtArbeidsPlanDato.Day.ToString()].ToolTipText = "Fra arbeidsplan - " + drv["Funksjon"].ToString();
                            row.Cells[dtArbeidsPlanDato.Day.ToString()].Style.BackColor = Color.LightBlue;
                        }
                    }
                }
                       
            }
 
            DateTime dtArbeidsplanAvvikDato;
            DataView dvArbeidsplanAvvik = new DataView(dtArbeidsplanAvvik);
            dvArbeidsplanAvvik.RowFilter = "[Gjelder dato] >= '#" + dtFørsteIMåneden.ToString() + "#' AND  [Gjelder dato] <= '#" + dtsisteIMåneden.ToString() + "#'";
            teller = 0;
            foreach (DataRowView drArbeidsplanAvvik in dvArbeidsplanAvvik)
            {
                DataGridViewRow row = dgv.Rows
                    .Cast<DataGridViewRow>()
                    .Where(r => r.Cells["Brukernavn"].Value.ToString().Equals(drArbeidsplanAvvik["Brukernavn"].ToString()))
                    .FirstOrDefault();
                if (row != null)
                {
                    dtArbeidsplanAvvikDato = Convert.ToDateTime(drArbeidsplanAvvik["Gjelder dato"].ToString());
                    teller = dtArbeidsplanAvvikDato.Day;
                    row.Cells[teller.ToString()].Style.BackColor = Color.Green;
                    row.Cells[teller.ToString()].ToolTipText = "Arbeidsplan avvik - " + drArbeidsplanAvvik["Tekst"].ToString();
                }   
            }
 

            string[] radString2 = new string[dgv.Columns.Count];
            int Antall = 0;
            radString2[0] = "Summering";
            radString2[1] = "Antall på jobb";
            radString2[2] = "";
            foreach (DataGridViewColumn dgvc in dgv.Columns)
            {
                if(_003_Util.Snacks.IsInteger(dgvc.Name))
                {
                    Antall = 0;
                    foreach (DataGridViewRow dgrv in dgv.Rows)
                    {
                        if (dgrv.Cells[dgvc.Name].Value != null)
                        {
                            if ((dgrv.Cells[dgvc.Name].Value.ToString() == "Jobb") || (dgrv.Cells[dgvc.Name].Value.ToString().Equals(dgrv.Cells["Avdeling"].Value.ToString(), StringComparison.CurrentCultureIgnoreCase)))
                            {
                                Antall++;
                            }
                        }
                    }
                    if(Antall!=0)
                        radString2[Convert.ToInt32(dgvc.Name)+2] = Antall.ToString();
                }
            }
            
            dgv.Rows.Add(radString2);
            DataGridViewBand band = dgv.Rows[dgv.Rows.Count - 1];
            DataGridViewCellStyle style = new DataGridViewCellStyle();
            style.BackColor = Color.WhiteSmoke;
            band.DefaultCellStyle = style;
            
            dgv.Rows[dgv.Rows.Count - 1].DefaultCellStyle.Font = new Font("Times New Roman", 9, FontStyle.Bold);
 
            Antall = 0;
            radString2 = new string[dgv.Columns.Count];
            radString2[0] = "Summering";
            radString2[1] = "Antall ikke på jobb";
            radString2[2] = "";
            foreach (DataGridViewColumn dgvc in dgv.Columns)
            {
                if (_003_Util.Snacks.IsInteger(dgvc.Name))
                {
                    Antall = 0;
                    foreach (DataGridViewRow dgrv in dgv.Rows)
                    {
                        if (dgrv.Index < dgv.Rows.Count-1)
                        {
                            if (dgrv.Cells[dgvc.Name].Value != null)
                            {
                                if ((dgrv.Cells[dgvc.Name].Value.ToString() != "Jobb") && (!dgrv.Cells[dgvc.Name].Value.ToString().Equals(dgrv.Cells["Avdeling"].Value.ToString(), StringComparison.CurrentCultureIgnoreCase)))
                                {
                                    if (dgrv.Cells[dgvc.Name].Value.ToString() != "")
                                        Antall++;
                                }
                            }
                        }
                    }
                    if (Antall != 0)
                        radString2[Convert.ToInt32(dgvc.Name) + 2] = Antall.ToString();
                }
            }
            dgv.Rows.Add(radString2);
            band = dgv.Rows[dgv.Rows.Count - 1];
            style = new DataGridViewCellStyle();
            style.BackColor = Color.WhiteSmoke;
            band.DefaultCellStyle = style;
            dgv.Rows[dgv.Rows.Count - 1].DefaultCellStyle.Font = new Font("Times New Roman", 9, FontStyle.Bold);
            //dgv.Rows[dgv.Rows.Count - 1].Frozen = true;
            dgv.Refresh();
 
            if ((måned == dtIdag.Month) && (år == dtIdag.Year))
                if (dgv.Rows.Count > -1)
                {
                    dgv.CurrentCell = dgv[dtIdag.Day.ToString(), 0];
                    dgv.CurrentCell.Selected = true;
                }
 
            if (sender == null)
            { }
            else
            {
                if (sender.GetType().Equals(typeof(BackgroundWorker)))
                { //ikke gjør noe, blir satt til default i bgw workercompleted
                }
                else
                {
                    this.Cursor = Cursors.Default;
                    setSkjemaStatus("Ferdig denne måned", 100);
                }
            }
 
            dtStopp = DateTime.Now;
            ts = dtStopp - dtStart;
            //ca 144 millisekunder med alle i dataview

 
            this.toolStripStatusLabel1.Text = "Sist oppdatert: " + DateTime.Now.ToString() + " [" + AntallGangerKjørt + "][" + AntallGangerLastet + "]";
        }
The code is meant for experiment and will not look like this in future.
Posted 18-Nov-11 7:11am
MrDeej819
Edited 18-Nov-11 8:02am
v8
Comments
SAKryukov at 18-Nov-11 12:29pm
   
Please add to the tags: WinForms.
--SA

1 solution

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

I don't want to analyze suck a long code dump. It's not very likely anyone have enough enthusiasm to delve into it. Your approach to getting help is not very productive.
 
In principle, you could have some performance leak in your code, I don't know. The bottleneck could be outside of your code, in performance of you database server, network or other factors you cannot affect.
 
Do you need periodic database polling. I can only point out that background worker is a worse way of using a thread for this application, because it is designed for one-time task and has considerable overhead when you create an instance of it. Much better solution is using a "permanent" thread, that is a thread created using the thread constructor with life time nearly of a lifetime of your application. You can create a thread when your main form is first shown and keep it alive until it's closed.
 
You can throttle this thread by using calling System.Threading.EventWaitHandle.WaitOne in the main loop of the thread method. It will put the thread in the wait state. OS switched out the thread and never schedule it back to execution until it is waken up by the call to System.Threading.EventWaitHandle.Set done in other thread or thread abort. This way, the thread waste no CPU time while waiting, so you can put it to work only when you need it.
 
Now, you need the thread to notify progress/status to you UI thread.
 
You cannot call anything related to UI from non-UI thread. Instead, you need to use the method Invoke or BeginInvoke of System.Windows.Threading.Dispatcher (for both Forms or WPF) or System.Windows.Forms.Control (Forms only).
 
You will find detailed explanation of how it works and code samples in my past answers:
Control.Invoke() vs. Control.BeginInvoke()[^],
Problem with Treeview Scanner And MD5[^].
 
See also more references on threading:
How to get a keydown event to operate on a different thread in vb.net[^],
Control events not firing after enable disable + multithreading[^].
 
—SA
  Permalink  
Comments
MrDeej at 18-Nov-11 12:46pm
   
I have timed all the tableadapter.updates and they are consistent within acceptable timespans.
 
The datagridviewr.rows.add command is the one which is slow, i have isolated it (first code block). I can make a seperate call with delegate/Invoke, but the datagridview is created in the first part of code. I will update code block one now.
 
And forgive if english is bad, i speak norwegian mostly :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 OriginalGriff 587
1 Sergey Alexandrovich Kryukov 479
2 Maciej Los 305
3 Mathew Soji 195
4 BillWoodruff 170
0 OriginalGriff 7,356
1 Sergey Alexandrovich Kryukov 6,777
2 DamithSL 5,461
3 Manas Bhardwaj 4,916
4 Maciej Los 4,475


Advertise | Privacy | Mobile
Web02 | 2.8.1411023.1 | Last Updated 18 Nov 2011
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100