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

时间:2016-04-27 01:29:59

标签: 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;

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;
            }
        }
    }
}

当我点击button1时,它开始每秒钟开始按空间,但是当我再次点击它以关闭它时,应用程序冻结并且它会持续按空间。我已经尝试了多种其他方式,但似乎无法弄清楚我是如何一次做两件事的,因为我被锁定在while循环中。

1 个答案:

答案 0 :(得分:3)

调用Thread.Sleep()将阻止UI线程。请尝试使用async / await。

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

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

<强>更新

您可以使用Timer代替。

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;
    }
}