播放声音文件后启动计时器,避免锁定GUI

时间:2013-10-05 19:47:06

标签: c# user-interface

我正在尝试制作一个GUI,在点击按钮后首先播放声音文件,播放后,它会启动一个计时器。

现在我发现获得此行为的最简单方法是在GUI内同步播放声音文件。这样GUI'阻止'并且只在声音文件播放完毕后启动计时器。

问题在于:

我没想到声音文件会这么长,但是有些篇幅很长,导致GUI显示“程序无响应”。

现在我该怎样做才能在播放声音后仍然启动计时器但没有锁定GUI?

我正在考虑使用一个任务但是检查任务是否完成仍然可能会锁定GUI。

我可以做些什么来完成这项工作?

更新

此代码在另一个Thread中运行,以便在GUI中启动计时器,使用以下代码(使用Marc Gravell提供的解决方案here

        //start timer after playing sound source:
        this.Invoke((MethodInvoker)delegate
        {
            if (!timer.Enabled)
                timer.Start();
        });

2 个答案:

答案 0 :(得分:1)

使用thread的非常简单的任务。以下是如何完成此任务的示例:

private void button1_Click(object sender, EventArgs e)
    {
        new System.Threading.Thread(testMethod).Start(); //starting a new thread
    }

    public void testMethod() //method will play sound and start timer after that
    {
        System.Media.SoundPlayer sp = new System.Media.SoundPlayer(filepath);
        sp.Play();
        timer1.Start();
    }

答案 1 :(得分:0)

使用线程。按下按钮时,在线程中启动计时器。这个线程应该停止声音。该线程不会阻止您的UI或使其无法响应。