2

I am having a chart with two series primary and secondary y-axis.I want to add values to chart using delegates.When I am adding,getting "cross thread operation not valid" exception. Please refer my code below.

    public delegate void SetTextDel(string Xvalue,double Y1value,double 

    Y2Value);
    Thread Thread1=new Thread(createGraph);

    private void SetText(string XValue,double Y1Value,double Y2Value)
    {
         if (this.chart1.InvokeRequired)
         {
             this.chart1.Series[0].Points.AddXY(XValue, Y1Value);        
             this.chart1.Series[1].Points.AddXY(XValue, Y2Value);       
         }       
    }

    private void createGraph()  
    { 
        while(true)
        { 
             string time;
             int  Y1value =0;
             int  Y2value =0;

             time="abc";
             Y1value = 10;
             Y2value = 20;

             SetTextDel = new SetTextDel(SetText);
             SetText(time,oilvalue,tempvalue);

             Y1value +=5;
             Y2value +=5;
        }       
   }

   private void startbtn_Click(object sender, EventArgs e)
   {
       Thread1.Start();
   }
sowjanya attaluri
  • 903
  • 2
  • 9
  • 27
  • 1
    If `InvokeRequired` is `true` then you actually suppose to invoke, see [this](http://stackoverflow.com/a/142069/1997232) answer. – Sinatr Jan 04 '16 at 15:31

1 Answers1

4

Replace

         this.chart1.Series[0].Points.AddXY(XValue, Y1Value);        
         this.chart1.Series[1].Points.AddXY(XValue, Y2Value);  

with this if your class derives from Form:

         BeginInvoke((Action)(() => {
             this.chart1.Series[0].Points.AddXY(XValue, Y1Value);        
             this.chart1.Series[1].Points.AddXY(XValue, Y2Value);  
         }));

or with this if your class derives from Page:

         Dispatcher.BeginInvoke((Action)(() => {
             this.chart1.Series[0].Points.AddXY(XValue, Y1Value);        
             this.chart1.Series[1].Points.AddXY(XValue, Y2Value);  
         }));
rsteward
  • 1,146
  • 2
  • 8
  • 9