这是一个游戏:用户可以将鼠标悬停在多个元素上,但只有当鼠标停留在500毫秒以上时才会调用一个函数。如果用户将鼠标移到另一个元素上,则从500ms开始倒计时重启。 但是,如果用户点击项目倒计时,则会停止直到其他元素悬停。
这是我的尝试,但由于取消是异步的,因此无法重新启动BackgroundWorker。
public BackgroundWorker bw = new BackgroundWorker();
private void Element_MouseEnter(object sender, MouseEventArgs e)
{
bw.DoWork += (snd, args) =>
{
int i = 500; //500ms
while (i > 0)
{
if (bw.CancellationPending) break;
Thread.Sleep(10);
i = i - 10;
}
};
bw.RunWorkerCompleted += (snd, args) =>
{
RunSomething(); //500 ms are out, nothing was clicked
}
if (bw.IsBusy) bw.CancelAsync();
bw.RunWorkerAsync();
}
private void Element_Clicked(object sender, MouseEventArgs e)
{
bw.CancelAsync();
}
必须有更好的方法......
答案 0 :(得分:3)
private CancellationTokenSource tokenSource;
private async void button1_MouseEnter(object sender, EventArgs e)
{
if (tokenSource != null)
tokenSource.Cancel();
tokenSource = new CancellationTokenSource();
try
{
await Task.Delay(500, tokenSource.Token);
if (!tokenSource.IsCancellationRequested)
{
//
}
}
catch (TaskCanceledException ex) { }
}
private void button1_Click(object sender, EventArgs e)
{
tokenSource.Cancel();
}