我有一个程序可以根据用户在变为绿色时点击按钮的速度来检查用户反应时间。我希望在单击按钮后在后台运行时正在运行的功能。
我虽然使用Task它会使它异步,但似乎并非如此。我知道有一个等待,可能我应该以某种方式返回它被调用的地方,但我找到解决方案时遇到了问题。
到目前为止我的代码看起来像这样
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();
}
}
答案 0 :(得分:0)
根据我编辑帖子的评论,更准确地反映了您的要求。删除异步并等待按钮的单击事件并替换System.Threading.Thread.Sleep(... with await Task.Delay(...这样你就不必在button1上使用BeginInvoke而且只需要单独的线程将是Task.Delay(...
UI将在Task.Delay期间响应(...然后在延迟结束时从中断处继续。
public partial class Reaction : Form
{
Stopwatch timer;
bool start = false;
public Reaction()
{
...
}
public async Task Test()
{
if (start)
{
...
}
else
{
Random rnd = new Random();
int number = rnd.Next(1, 10000);
// Replace Thread.Sleep with Task.Delay
await Task.Delay(3000 + number);
timer = Stopwatch.StartNew();
button1.BackColor = Color.Green;
button1.Text = "CLICK";
start = true;
}
}
// Make button1_Click not async and remove await
private void button1_Click(object sender, EventArgs e)
{
button1.BackColor = Color.Red;
button1.Text = "Dont click";
Test();
}
}