在背景中播放哔声
问题描述:
从其他网站的一些参考,我已经开发了一个代码,检查项目是否可供出售。
如果该项目不可用,它应该在背景中发出一个哔声以及一个对话框(重试/取消)。
此外,如果用户点击重试,嘟嘟声不应该停止。
否则单击取消应停止背景中的嘟嘟声。
代码中,我使用
在背景中播放哔声
if()
{
Item exists code
}
else
{
//Item Not found
retry();
}
public void retry()
{
Thread beepThread = new Thread(new ThreadStart(PlayBeep));
beepThread.IsBackground = true;
if (MessageBox.Show("Item not found", "Alert", MessageBoxButtons.RetryCancel) == DialogResult.Retry)
{
beepThread.Start();
retry();
}
else
{
beepThread.Abort();
Console.Beep(500, 1);
return;
}
}
private void PlayBeep()
{
Console.Beep(500, int.MaxValue);
}
使用上面的代码中,播放的声音,当我点击重试但我想,因为它进入else条件使其尽快发挥(当项目是没有找到)
有什么建议吗?
答
您应该在出现消息框之前开始发出哔声。为了不会有太多未使用的threads
,你必须在两种情况下中止它们。
最后,我会建议使用while(true)
循环,以获得无尽的嘟嘟声。
public void retry()
{
Thread beepThread = new Thread(new ThreadStart(PlayBeep));
beepThread.IsBackground = true;
beepThread.Start();
if (MessageBox.Show("Item not found", "Alert", MessageBoxButtons.RetryCancel) == DialogResult.Retry)
{
beepThread.Abort();
retry();
}
else
{
beepThread.Abort();
Console.Beep(500, 1);
return;
}
}
private void PlayBeep()
{
while(true)
{ Console.Beep(500, int.MaxValue); }
}
谢谢@Jibbow它真的帮助:) –