我试图:
我已经设法做到这一点,但感觉就像一个解决方法,因为我被迫将代码放入synthesizer_SpeakCompleted
方法。到目前为止,我的代码如下。我希望有正确方法的任何信息。
public void TestDelay()
{
DoSomeSpeechAndSignalWhenItsDone();
}
public void DoSomeSpeechAndSignalWhenItsDone()
{
form.AccessTxtQnReport += "This is written before the speech" + Environment.NewLine;
synthesizer.SpeakCompleted += new EventHandler<SpeakCompletedEventArgs>(synthesizer_SpeakCompleted);
synthesizer.SpeakAsync("this is a load of speech and it goes on quite a while");
}
async void synthesizer_SpeakCompleted(object sender, SpeakCompletedEventArgs e)
{
//we get here when speech has finished
form.AccessTxtQnReport += "This is written after the speech" + Environment.NewLine;
synthesizer.SpeakCompleted -= new EventHandler<SpeakCompletedEventArgs>(synthesizer_SpeakCompleted);
// Do a delay
await Task.Delay(3000);
form.AccessTxtQnReport += "This is written after the delay" + Environment.NewLine;
// this makes it cycle round for ever
TestDelay();
}
编辑&gt;谢谢你的回复。我现在已经将代码更改为这似乎有效,并且看起来更好一些:
// attempt delay using TaskCompletionSource
private TaskCompletionSource<bool> tcs;
public void TestDelay()
{
tcs = new TaskCompletionSource<bool>();
DoSomeSpeechAndSignalWhenItsDone();
}
private async void DoSomeSpeechAndSignalWhenItsDone()
{
form.AccessTxtQnReport += "This is written before the speech" + Environment.NewLine;
synthesizer.SpeakCompleted += new EventHandler<SpeakCompletedEventArgs>(synthesizer_SpeakCompleted);
synthesizer.SpeakAsync("this is a load of speech and it goes on quite a while");
await tcs.Task;
form.AccessTxtQnReport += "This is written after the speech" + Environment.NewLine;
await Task.Delay(2000);
form.AccessTxtQnReport += "This is written after the delay" + Environment.NewLine;
// repeat the process ad nauseam
TestDelay();
}
private void synthesizer_SpeakCompleted(object sender, SpeakCompletedEventArgs e)
{
//we get here when speech has finished
synthesizer.SpeakCompleted -= new EventHandler<SpeakCompletedEventArgs>(synthesizer_SpeakCompleted);
//set the task as completed:
tcs.SetResult(true);
}