我是异步编程的新手,我想知道你是否可以伪造c#异步方法使其像同步一样工作?或者,如果您可以在执行另一种方法之前让它等待它完成?
就我而言:
await Speak("Do you want me to call 123 ?");
if (isComplete)
{
PhoneCallTask phone = new PhoneCallTask();
phone.PhoneNumber = "123";
phone.Show();
}
await Speak("blabla");
isComplete是全局布尔值..
这是Speak方法:
private async Task Speak(string text)
{
SpeechSynthesizer synth = new SpeechSynthesizer();
await synth.SpeakTextAsync(text);
isComplete = true;
}
它说的是第一个文本,而不是显示对话框..在对话框崩溃后它崩溃了..
答案 0 :(得分:1)
您可以使用await
关键字
请参阅以下来自MSDN
的示例// Declare the SpeechSynthesizer object at the class level.
SpeechSynthesizer synth;
// Handle the button click event.
private async void SpeakFrench_Click_1(object sender, RoutedEventArgs e)
{
// Initialize the SpeechSynthesizer object.
synth = new SpeechSynthesizer();
// Query for a voice that speaks French.
IEnumerable<VoiceInformation> frenchVoices = from voice in InstalledVoices.All
where voice.Language == "fr-FR"
select voice;
// Set the voice as identified by the query.
synth.SetVoice(frenchVoices.ElementAt(0));
// Count in French.
await synth.SpeakTextAsync("un, deux, trois, quatre");
}