System.Timers.Timer如何操作能传递win窗体label的text?急!急!急!
///定时器用来定时刷新
public System.Timers.Timer RWIOTimer = new System.Timers.Timer();
public int i=0;
public void initRWIOTimer()
{
RWIOTimer.Elapsed += new System.Timers.ElapsedEventHandler(RWIOTimer_Elapsed);
RWIOTimer.Interval = 2000;
RWIOTimer.AutoReset = true;
}
/// 定时器事件
private void RWIOTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
i+=1;
label1.text=i.tostring();
}
private void Form1_Load(object sender, EventArgs e)
{
RWIOTimer.Enabled = true;
initRWIOTimer();
}
我想让label每隔2秒钟刷新一次数据,可是提示错误:用户代码未处理,线程间操作无效,从不是创建控件label1的线程访问它。
好像要用到委托,但对委托不了解,看了相关委托的介绍,看得一头雾水,有哪位知道这样的问题该怎么处理???
很着急,赶紧帮帮忙!
------解决方案--------------------private delegate void UpdateText(int i);
private void OnUpdateText(int i)
{
if(this.InvokeRequired)
{
UpdateText dele = new UpdateText(this.OnUpdateText);
this.Invoke(dele, new object[]{i});
}
else
label1.text=i.tostring();
}
------解决方案--------------------for example:
private System.Timers.Timer myTimer;
private int count;
public delegate void MyInvoke(string str);
public Form1()
{
InitializeComponent();
count = 0;
myTimer = new System.Timers.Timer();
myTimer.Interval = 2000;
myTimer.Elapsed += new System.Timers.ElapsedEventHandler(myTimer_Elapsed);
myTimer.Enabled = true;
}
private void UpdateUI(string str)
{
this.label1.Text = str;
}
void myTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
//显示Lable
MyInvoke mi = new MyInvoke(this.UpdateUI);
this.BeginInvoke(mi, new object[] { count.ToString() });
count++;
}