0

我只是想通过单击按钮来播放 .wav 声音,通过使用 .Net 4.0 - Task.Factory 选择的次数,它播放得很好,但是有一刻我想通过其他按钮快速停止这个声音,我可以说停止按钮,但它并没有快速停止声音,它只有在完全播放后才会停止......下面是我的代码......

CancellationTokenSource tokenSource = new CancellationTokenSource();

private void btnStartPlaying_Click(object sender, EventArgs e)
{
            tokenSource = new CancellationTokenSource();                       
            List<Task> tasks = new List<Task>();
            var ui = TaskScheduler.FromCurrentSynchronizationContext();
            int playTimes = 3;

            var compute = Task.Factory.StartNew(() =>
            {
                Playing(playTimes);

            }, tokenSource.Token);
            tasks.Add(compute);

            var displayResults = compute.ContinueWith(resultTask =>                                     
                                                        Environment.NewLine,
                                                        CancellationToken.None,
                                                        TaskContinuationOptions.OnlyOnRanToCompletion,
                                                    ui);
            var displayCancelledTasks = compute.ContinueWith(resultTask =>                                               
                                                                Environment.NewLine,
                                                                CancellationToken.None,
                                                                TaskContinuationOptions.OnlyOnCanceled, ui);            
            Task.Factory.ContinueWhenAll(tasks.ToArray(),
                result =>
                {

                }, CancellationToken.None, TaskContinuationOptions.None, ui);
}


private void btnStopPlaying_Click(object sender, EventArgs e)
{
      tokenSource.Cancel();            
}

public void Playing(int times)
{
     try
     {
      using (SoundPlayer player = new SoundPlayer("mySoundFile.wav"))
                {
                    for (int i = 0; i < times; i++)
                    {
                        tokenSource.Token.ThrowIfCancellationRequested();
                        player.PlaySync();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Stopped!!!!!");
            }
}
4

1 回答 1

0

您不是要立即停止播放。而是要停止文件重复播放。

想象一下,当代码已经开始执行时,您取消了任务player.PlaySync();。应用程序无法知道已请求取消。它仅在下一次迭代期间引发任务取消异常。

Task 类也强调合作取消,这意味着您不希望声音突然停止播放。

于 2012-10-20T10:12:59.357 回答