How to synchronise an asynchronous operation?

2019-08-28 21:02发布

问题:

I have been looking around in this forum as well as in MSDN but I couldn't really find a proper solution for my problem. Probably my approach is not good. I have the below simple class which has 1 simple method ("PlayAudioFile"). All I want to do is to wait for the playback to complete before letting the method finish and moving on. Since the .Play() is asynchronous, method finishes before playback is completed which is not good for me because I want to playback several files synchronously (1 after the other). I have tried to use AutoResetEvent w/o luck because when playback is over, I dont get into the "MediaEnded" callback.... 1 solution I dont want to use is to have a while () loop busy waiting for a flag raised inside the MediaEnded signalling that the playback is done. It just doesnt seem right.

Any ideas?

public class Audio
{
    AutoResetEvent are = new AutoResetEvent(false);
    public void PlayAudioFile(string file)
    {
        MediaPlayer mediaPlayer = new MediaPlayer();
        mediaPlayer.MediaEnded += m_MediaEnded;
        mediaPlayer.Open(new Uri(file));
        mediaPlayer.Play();
        are.WaitOne();

    }

    private void m_MediaEnded(object sender, EventArgs e)
    {
        MediaPlayer mediaPlayer = (MediaPlayer)sender;
        mediaPlayer.Close();
        mediaPlayer = null;
        are.Set();
    }

}

回答1:

If you are using .Net framework>= 4.5, you can utilize async/await. Your code can be something like this(sorry I code it blindly)

await PlayAudioFile(somefile);

public Task PlayAudioFile(string file)
{
    var tcs = new TaskCompletionSource<bool>();
    MediaPlayer mediaPlayer = new MediaPlayer();
    mediaPlayer.MediaEnded += (sender, e) =>
        {
            mediaPlayer.Close();
            tcs.TrySetResult(true);
        };
    mediaPlayer.Open(new Uri(file));
    mediaPlayer.Play();
    return tcs.Task;
}