C# 如何避免使用异步方法windows phone 8.1
我正在创建一个windows phone 8.1应用程序。当应用程序启动时,应用程序会提示用户拨打特定的电话号码。它是通过声音来实现的。应用程序告知指令后,显示电话通话对话框。 代码如下:C# 如何避免使用异步方法windows phone 8.1,c#,asynchronous,speech-recognition,windows-phone-8.1,speech-to-text,C#,Asynchronous,Speech Recognition,Windows Phone 8.1,Speech To Text,我正在创建一个windows phone 8.1应用程序。当应用程序启动时,应用程序会提示用户拨打特定的电话号码。它是通过声音来实现的。应用程序告知指令后,显示电话通话对话框。 代码如下: public MainPage() { this.InitializeComponent(); this.NavigationCacheMode = NavigationCacheMode.Required; StartSpeaking("Please
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
StartSpeaking("Please call number !");
CallDialog();
}
private async void StartSpeaking(string text)
{
MediaElement mediaElement = this.media;
// The object for controlling the speech synthesis engine (voice).
var synth = new Windows.Media.SpeechSynthesis.SpeechSynthesizer();
// Generate the audio stream from plain text.
SpeechSynthesisStream stream = await synth.SynthesizeTextToStreamAsync(text);
// Send the stream to the media object.
mediaElement.SetSource(stream, stream.ContentType);
mediaElement.Play();
}
private async void CallDialog()
{
Windows.ApplicationModel.Calls.PhoneCallManager.ShowPhoneCallUI("123", "123");
var messageDialog = new Windows.UI.Popups.MessageDialog("call ended", "Text spoken");
await messageDialog.ShowAsync();
}
问题是我必须使用synth.synthezettexttostreamasync方法,这是一种异步方法,所以调用对话框会在显示文本之前显示。如何避免这种情况?
异步任务
方法应该被接受;只有async void
方法才应该避免(它们只应该用作事件处理程序)。我有一本书
在您的情况下,您可以使用async void
事件处理程序(例如,对于Loaded
事件),并使您的方法async Task
而不是async void
和等待它们:
async void MainPage_Loaded(..)
{
await StartSpeakingAsync("Please call number !");
await CallDialogAsync();
}
private async Task StartSpeakingAsync(string text);
private async Task CallDialogAsync();
更新
要(异步)等待媒体播放,您需要挂接一个事件,通知您播放完成MediaEnded
看起来是个不错的选择。像这样的方法应该会奏效:
public static Task PlayToEndAsync(this MediaElement @this)
{
var tcs = new TaskCompletionSource<object>();
RoutedEventHandler subscription = null;
subscription = (_, __) =>
{
@this.MediaEnded -= subscription;
tcs.TrySetResult(null);
};
@this.MediaEnded += subscription;
@this.Play();
return tcs.Task;
}
是的,我明白这一点,但即使我这样做,我仍然会在应用程序启动时收到呼叫对话框,而不是在它之前请拨打电话号码。
private async Task SpeakAsync(string text)
{
MediaElement mediaElement = this.media;
var synth = new Windows.Media.SpeechSynthesis.SpeechSynthesizer();
SpeechSynthesisStream stream = await synth.SynthesizeTextToStreamAsync(text);
mediaElement.SetSource(stream, stream.ContentType);
await mediaElement.PlayToEndAsync();
}