简体   繁体   English

C#中的异步和等待关键字

[英]Async and Await keywords in C#

I'm taught asynchronous programming helps to spawn multiple threads so that the async thread never impacts the UI and the subsequent lines of code need not wait until the completion of the previous thread. 我教过异步编程有助于产生多个线程,以便异步线程永远不会影响UI,后续代码行不需要等到前一个线程完成。 Now the idea is I'm calling a flyout asynchronously and while it is being called I'm wanting to hide the bottom appbar. 现在的想法是我异步调用一个弹出窗口,当它被调用时我想要隐藏底部的appbar。 But surprisingly when implemented, the appbar is not hidden until the flyout is opened and dismissed. 但令人惊讶的是,在实施时,在弹出窗口打开和解除之前,appbar不会被隐藏。 Couldn't understand as to why. 无法理解为什么。 Here's the abstract piece of code. 这是抽象的代码片段。 your inputs will help me to understand async processes better. 您的输入将帮助我更好地理解异步过程。

private async void OnClick(object sender, TappedRoutedEventArgs e) 
{

    var flyout = new cmpWebA.Flyout();

    await flyout.ShowAsync();

    this.BottomAppBar.IsOpen = false;

}

Invoking an asynchronous operation involves two parts: starting it, and awaiting its completion. 调用异步操作涉及两个部分:启动它,等待它完成。

You code currently starts the operation flyout.ShowAsync(); 您的代码当前启动操作flyout.ShowAsync(); , then awaits its completion ( await ) and then hides the bottom bar ( this.BottomAppBar.IsOpen = false; ). ,然后等待它完成( await ),然后隐藏底栏( this.BottomAppBar.IsOpen = false; )。

If you want to hide the bottom bar while ShowAsync is running, hide it before you start it and show it when it's completed: 如果要在ShowAsync运行时隐藏底栏, ShowAsync在启动之前将其隐藏,并在完成时显示:

private async void OnClick(object sender, TappedRoutedEventArgs e)
{
    this.BottomAppBar.IsOpen = false;

    var flyout = new cmpWebA.Flyout();
    await flyout.ShowAsync();

    this.BottomAppBar.IsOpen = true;
}

You can also start ShowAsync first, then hide the bottom bar, then await completion and then show the bottom bar: 您也可以先启动ShowAsync ,然后隐藏底栏,然后等待完成,然后显示底栏:

private async void OnClick(object sender, TappedRoutedEventArgs e)
{
    var flyout = new cmpWebA.Flyout();
    var task = flyout.ShowAsync();

    this.BottomAppBar.IsOpen = false;

    await task;

    this.BottomAppBar.IsOpen = true;
}

Asynchronousity isn't the same thing as concurrency. 异步与并发性不同。 An asynchronous operation certainly can be implemented with a thread, it however isn't all that common. 一个异步操作当然可以用一个线程实现,但它并不常见。 You for example want to use await when you are waiting for a slow I/O operation to complete. 例如,您希望在等待慢速I / O操作完成时使用等待。 Which is done by built-in support for overlapped I/O in the operating system, it doesn't require a thread. 这是通过内置支持操作系统中的重叠I / O来完成的,它不需要线程。

If you want true concurrency, having more than one thread working on getting a job done, then there is no substitute for actually creating the threads. 如果你想要真正的并发,有多个线程在完成工作,那么实际创建线程是无可替代的。 Or Tasks. 或任务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM