如何同步异步操作? [英] How to synchronise an asynchronous operation?

查看:127
本文介绍了如何同步异步操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在这个论坛以及MSDN中四处逛逛,但是我找不到真正适合我问题的合适解决方案.可能我的方法不好. 我有下面的简单类,其中有1个简单方法("PlayAudioFile").我要做的就是在方法完成并继续之前,等待播放完成.由于.Play()是异步的,因此方法在播放完成之前完成,这对我不利,因为我想同步播放多个文件(一个接一个).我尝试使用没有运气的AutoResetEvent,因为当播放结束时,我没有进入"MediaEnded"回调....我不希望使用的1个解决方案是让while()循环忙于等待标志升起在MediaEnded信号中,表示已完成播放.似乎不正确.

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.

有什么想法吗?

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

}

推荐答案

如果使用的是.Net framework> = 4.5,则可以使用async/await.您的代码可以是这样的(对不起,我盲目地编写了代码)

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

这篇关于如何同步异步操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆