我有一个程序,当它变成绿色时,它会根据按钮上点击按钮的速度来检查用户反应时间。我希望点击按钮后在后台运行的功能。如何在后台执行按钮运行操作
我虽然通过使用任务它会使它异步,但它似乎并非如此。我知道有一个等待,可能我应该让它返回到它被称为的地方,但我有一个问题找到解决方案。
到目前为止我的代码看起来像这样
public partial class Reaction : Form
{
Stopwatch timer;
bool start = false;
public Reaction()
{
InitializeComponent();
button1.Text = "START";
button1.BackColor = Color.Red;
}
public async Task Test()
{
if (start)
{
timer.Stop();
TimeSpan timespan = timer.Elapsed;
string timeString = String.Format("{0:00}:{1:00}:{2:00}", timespan.Minutes, timespan.Seconds, timespan.Milliseconds/10);
MessageBox.Show(timeString);
button1.BackColor = Color.Red;
button1.Text = "START";
start = false;
}
else
{
Random rnd = new Random();
int number = rnd.Next(1, 10000);
System.Threading.Thread.Sleep(3000 + number);
timer = Stopwatch.StartNew();
button1.BackColor = Color.Green;
button1.Text = "CLICK";
start = true;
}
}
private async void button1_Click(object sender, EventArgs e)
{
button1.BackColor = Color.Red;
button1.Text = "Dont click";
await Test();
}
}
为什么不要在新线程中运行“背景”代码像这样: 线程T =新线程(测试); T.start(); – Taco2
您应该使用Task.Delay(1000);而不是Thread 。睡眠 –
Usin g Task.Delay(1000);并不能解决问题。这只是等待“等待” – Taco2