I have the following code which uses Events and Deligate, I need to have a
timer in a library and update UI everytime the event fires.
but I am getting the following error in Reading method and the following
statement this.label1.Text = val.ToString();:
Cross-thread operation not valid: Control 'label1' accessed from a thread
other than the thread it was created on.
How can I fix this problem?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using LabExampleLib;
namespace LabExample
{
public partial class Form1 : Form
{
TimerLib tl = new TimerLib();
int i = 0;
public Form1()
{
InitializeComponent();
tl.Reading += new TimerLib.Calculate(Reading);
}
void Reading(double val)
{
i++;
this.label1.Text = val.ToString();
}
private void button1_Click(object sender, EventArgs e)
{
tl.Start();
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Timers;
namespace LabExampleLib
{
public class TimerLib
{
public delegate void Calculate(double val);
public event Calculate Reading;
private double i = 0;
System.Timers.Timer aTimer;
public TimerLib()
{
aTimer = new System.Timers.Timer();
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
}
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
i++;
OnReading(i);
}
public void Start()
{
aTimer.Interval = 1000;
aTimer.Enabled = true;
}
protected void OnReading(double val)
{
if (Reading != null)
Reading(val);
}
}
}
Thank You
Peter