我只是想通过单击按钮来播放 .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!!!!!");
}
}