让一个事件等待另一个事件完成 - Old Shool



我需要这样做,但没有 async/await 关键字(我的应用程序是用 .NET Framework 4.0 (

TaskCompletionSource<bool> tcs = null;
private async void Button_Click(object sender, RoutedEventArgs e)
{
    tcs = new TaskCompletionSource<bool>();
    await tcs.Task;
    WelcomeTitle.Text = "Finished work";
}
private void Button_Click2(object sender, RoutedEventArgs e)
{
    tcs?.TrySetResult(true);
}

知道吗?

您需要手动将延续附加到任务。这就是 async-await 旨在减轻的负担。

TaskCompletionSource<bool> tcs = null;
private void Button_Click(object sender, RoutedEventArgs e)
{
    tcs = new TaskCompletionSource<bool>();
    tcs.Task.ContinueWith((_) =>
    {
        WelcomeTitle.Text = "Finished work";
    }, TaskContinuationOptions.ExecuteSynchronously);
}
private void Button_Click2(object sender, RoutedEventArgs e)
{
    tcs?.TrySetResult(true);
}

最新更新