2016-09-22 64 views
3

我從main方法調用:如何在C#中將異步方法與同步方法結合起來?

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

回答

7

這聽起來像你真正想要的是當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; 
    } 
} 
+0

哇謝謝老兄它就像一個魅力... – Learner

+0

會不會'Task.FromResult'比'TaskCompletionSource'好# –

+1

@MrinalKamboj:你究竟如何用它來解決手頭的問題?它如何幫助你異步等待事件發生? –