通过引用其他网站上的一些引用资料,我开发了一个代码来检查某项商品是否可供出售。
如果该项目不可用,它应该在背景中发出哔哔声以及一个对话框(重试/取消)。此外,如果用户单击重试,则不应停止发出哔声,否则单击取消应在后台停止哔声。 我使用的代码

                    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);
    }

使用上面的代码,当我单击重试时播放声音,但我希望它在进入其他条件时立即播放(当未找到项目时)
有什么建议么?

最佳答案

您应该在出现消息框之前立即发出蜂鸣声。为了没有太多未使用的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); }
    }

关于c# - 在后台播放提示音,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32438111/

10-10 13:48
查看更多