在背景中播放哔声

时间:2015-09-07 11:54:51

标签: c# audio

通过其他网站的一些参考,我开发了一个代码,用于检查商品是否可供销售。
如果项目不可用,它应该在背景中发出一声嘟嘟声和一个对话框(重试/取消)。

此外,如果用户点击重试,则不应停止发出哔哔声。
否则单击取消应停止后台的哔声。

我使用的代码

                    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条件时立即播放(当找不到项目时) 有什么建议?

1 个答案:

答案 0 :(得分:2)

您应该在消息框出现之前开始发出哔声。为了不使用太多未使用的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); }
    }
相关问题