C# 我的计时器出问题了

C# 我的计时器出问题了,c#,winforms,timer,C#,Winforms,Timer,我正在尝试制作一个计时器,它可以触发一个方法,每分钟更新一个文本框,作为一个时钟,这样在现实生活中每过一分钟,在游戏中就是一小时。以下是我目前掌握的代码: public partial class Terminal : Form { static int time; System.Timers.Timer timer1 = new System.Timers.Timer(); private void Terminal_Load(object sender, Event

我正在尝试制作一个计时器,它可以触发一个方法,每分钟更新一个文本框,作为一个时钟,这样在现实生活中每过一分钟,在游戏中就是一小时。以下是我目前掌握的代码:

public partial class Terminal : Form
{
    static int time;
    System.Timers.Timer timer1 = new System.Timers.Timer();

    private void Terminal_Load(object sender, EventArgs e)
    {
        time = 0;

        timer1.Elapsed += new ElapsedEventHandler(UpdateTime);
        timer1.Interval = 1000;
        timer1.AutoReset = true;

        GoToPage(Pages.Tasks);
        UpdateClock(time);
        timer1.Start();
    } //private void Terminal_Load(object sender, EventArgs e)

    private void UpdateTime(object source, ElapsedEventArgs eea)
    {
        if (time < 6) //the clock is not supposed to go any further than 6 am
            time++;
        UpdateClock(time);
    } //private static Task UpdateTime(int t)

    private void UpdateClock(int t)
    {
        if (time == 0)
        {
            timeBox.Text = "12 AM";
        } //if
        else if (time > 0 && time <= 6)
        {
            timeBox.Text = time + " AM"; //error appears here each time the timer elapses
        } //else if
    } //private void UpdateClock()
} //public partial class Terminal : Form
公共部分类终端:表单
{
静态整数时间;
System.Timers.Timer timer1=新的System.Timers.Timer();
私有无效终端加载(对象发送方,事件参数e)
{
时间=0;
timer1.appeased+=新的ElapsedEventHandler(UpdateTime);
计时器1。间隔=1000;
timer1.AutoReset=true;
GoToPage(页面、任务);
UpdateLock(时间);
timer1.Start();
}//私有无效终端加载(对象发送方,事件参数e)
私有void更新时间(对象源,ElapsedEventArgs eea)
{
if(time<6)//时钟不应超过上午6点
时间++;
UpdateLock(时间);
}//私有静态任务更新时间(int t)
私有void updatelock(int t)
{
如果(时间==0)
{
timeBox.Text=“12 AM”;
}//如果

否则,如果(time>0&&time您的问题来自于事件在运行用户界面(UI)的不同线程上触发的点。UI的所有控制元素都属于UI线程,系统将不允许您从其他线程对其进行操作

看起来您正在WinForms中工作,因此我建议使用命名空间
System.Windows.Forms
提供的。它在UI线程上运行,因此此异常将消失,无需使用
Invoke

System.Windows.Forms.Timer timer1 = new System.Windows.Forms.Timer();
此处调用的是事件,而不是经过的

timer1.Tick += UpdateTime;
您的方法看起来会有些不同:

private void UpdateTime(object sender, EventArgs e)
{

此计时器也将自动重新启动,直到您在计时器上调用
Stop()

使用BeginInvoke。您必须在GUI线程中设置“timeBox.Text”。如下所述:可能重复