我最近開始學習C#,我試圖在計時器的幫助下每分鐘重複一次方法。該方法更改標籤的值。但是,我收到以下錯誤:C# - Winforms - 重複定時器的幫助下的方法
$exception {"Cross-thread operation not valid: Control 'label1' accessed from a thread other than the thread it was created on."} System.Exception {System.InvalidOperationException}
我試過尋找解決方案,每個線程都讓我困惑。我不只需要正確的代碼,還需要解釋,因爲我想學習使用定時器和線程來操作UI。
下面是我的代碼:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Timers;
using System.Windows.Forms;
namespace Winforms_Timer_and_Thread
{
public partial class Form1 : Form
{
System.Timers.Timer myTimer = new System.Timers.Timer();
public Form1()
{
myTimer.Enabled = true;
InitializeComponent();
}
public void startMethod(object senter, ElapsedEventArgs e)
{
int cntr = 0;
cntr++;
label1.Text = "Executed: " + cntr.ToString();
}
private void button1_Click(object sender, EventArgs e)
{
label1.Text = "Started!";
myTimer.Enabled = true;
myTimer.Interval=(1*60*1000);
myTimer.Elapsed += new System.Timers.ElapsedEventHandler(startMethod);
}
}
}
看到的是https:// stackoverflow.com/questions/661561/how-to-update-the-gui-from-another-thread-in-c 您無法直接從非ui線程訪問用戶界面。 –
你也可以考慮改用System.Windows.Forms.Timer。 –
@James R.但是那麼可以每分鐘調用一次該方法嗎? – Tango