我如何在异步函数的末尾启动一个函数 c# UWP

how do I start a function at the end of an asynchronous function c# UWP

我在 c# UWP 中有这个简单的代码,其中 Windows.Media.SpeechSynthesis class 应用程序合成第一个字符串,我的问题是在第一个合成完成后合成第二个字符串。我知道通过制作一个包含 str1+str2 的唯一字符串是可能的,但是 运行 这段代码更复杂的场景是不可能的。(对不起,我的英语水平很低)

    public MainPage()
    {
        this.InitializeComponent();
        string str1 = "weather data"; 
        talk(Textmeteo);
        string str2 = "hello world";
        talk(str2);
    }

    public async void talk(string text)
    {
        // The media object for controlling and playing audio.
        MediaElement mediaElement = new MediaElement();

        // The object for controlling the speech synthesis engine (voice).
        SpeechSynthesizer synth = new 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();

    }

一如既往,使用 async 方法 return void 而不是 TaskTask<T>.
是个坏主意 当你 return 一个 Task 时,你可以简单地添加一个延续 ContinueWith:

public MainPage()
{
    this.InitializeComponent();
    string str1 = "weather data"; 
    Task talkingTask = talk(Textmeteo);
    string str2 = "hello world";
    talkingTask = talkingTask.ContinueWith(completedTask => talk(str2));
}

public async Task talk(string text)
{
    // await...
}

使方法 talk return 成为 Task 而不是 void.

public MainPage()
{
    this.InitializeComponent();
    MakeTalk();
}

private async void MakeTalk()
{
    // Surround by a try catch as we have async void.
    string str1 = "weather data"; 
    await talk(Textmeteo);
    string str2 = "hello world";
    await talk(str2);
}

public async Task talk(string text)
{
   // [...]
}