c#中异步方法与同步方法的结合

本文关键字:结合 同步方法 异步方法 | 更新日期: 2023-09-27 18:08:19

我从主方法中调用:

public MainPage()
{
  Text_to_Speech.changetospeech("Welcome to Nepal!", newmedia).Wait();
  mytxtblck.Text="Hello from Nepal!"
}

我真正想做的是Wait,直到说"欢迎来到尼泊尔",然后在mytextblck中写"你好"。

我已经尝试了几个线程,但是没有一个可以使它工作。

public async static Task changetospeech(string text, MediaElement mediaa)
{
   var synth = new SpeechSynthesizer();
   var voices = SpeechSynthesizer.AllVoices;
   synth.Voice = voices.First(x => x.Gender == VoiceGender.Female );
   SpeechSynthesisStream stream = await synth.SynthesizeTextToStreamAsync(text);
   MediaElement media = mediaa;
   media.SetSource(stream,stream.ContentType);
   media.Play();   
}

c#中异步方法与同步方法的结合

听起来你真正想要的是在MediaEnded事件被触发时触发文本更改。

可以在你的ChangeToSpeech方法中这样做,尽管它会有点难看:

public async static Task ChangeToSpeech(string text, MediaElement media)
{
    var synth = new SpeechSynthesizer();
    var voices = SpeechSynthesizer.AllVoices;
    synth.Voice = voices.First(x => x.Gender == VoiceGender.Female);
    SpeechSynthesisStream stream = await synth.SynthesizeTextToStreamAsync(text);
    var tcs = new TaskCompletionSource<int>();
    RoutedEventHandler handler = delegate { tcs.TrySetResult(10); };
    media.MediaEnded += handler;
    try
    {
        media.SetSource(stream, stream.ContentType);
        media.Play();
        // Asynchronously wait for the event to fire
        await tcs.Task;
    }
    finally
    {
        media.MediaEnded -= handler;
    }
}