Visual Studio C#while循环冻结表单应用程序

Visual Studio C#while循环冻结表单应用程序,c#,C#,这是我的密码: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Threading; nam

这是我的密码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;

namespace _8BB_2._0
{
    public partial class Form1 : Form
    {
        public static class globalVars
        {
            public static bool spacerunning = false;
        }

        public Form1()
        {
            InitializeComponent();
            globalVars.spacerunning = false;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (!globalVars.spacerunning)
            {
                globalVars.spacerunning = true;
                while (globalVars.spacerunning)
                {
                    Thread.Sleep(1000);
                    SendKeys.Send(" ");
                }
            }
            else if (globalVars.spacerunning)
            {
                globalVars.spacerunning = false;
            }
        }
    }
}
当我点击按钮1时,它开始像它应该的那样每秒点击空格,但当我再次尝试点击它关闭它时,应用程序冻结,它继续按空格。我尝试了多种其他方法,但似乎不知道如何一次做两件事,因为我被锁定在while循环中。

调用
Thread.Sleep()
将阻塞UI线程。尝试改用异步/等待

private async void button1_Click(object sender, EventArgs e)
{
    globalVars.spacerunning = !globalVars.spacerunning;

    while (globalVars.spacerunning)
    {
        await Task.Delay(1000);
        SendKeys.Send(" ");
    }
}
更新:

您可以使用
计时器

public class MainForm : Form
{
    private Timer timer = new Timer() { Interval = 1000 };

    public MainForm()
    {
        /* other initializations */

        timer.Enabled = false;
        timer.Tick += timer_Tick;
    }

    private void timer_Tick(object sender, EventArgs e)
    {
        SendKeys.Send(" ");
    }

    private void button1_Click(object sender, EventArgs e)
    {
        globalVars.spacerunning = !globalVars.spacerunning;
        timer.Enabled = globalVars.spacerunning;
    }
}

非常感谢。UI现在可以工作了,但当我点击按钮时它似乎没有停止?这是异步错误还是我的代码错误?代码正常,但如果选择发送空间,则可以按下按钮。