根据我的理解,async和await所做的主要事情之一是使代码易于编写和阅读-但使用它们是否等于生成后台线程来执行长时间的逻辑?

我目前正在尝试最基本的例子。我内联添加了一些注释。你能给我解释一下吗?

// I don't understand why this method must be marked as `async`.
private async void button1_Click(object sender, EventArgs e)
{
    Task<int> access = DoSomethingAsync();
    // task independent stuff here

    // this line is reached after the 5 seconds sleep from 
    // DoSomethingAsync() method. Shouldn't it be reached immediately? 
    int a = 1; 

    // from my understanding the waiting should be done here.
    int x = await access; 
}

async Task<int> DoSomethingAsync()
{
    // is this executed on a background thread?
    System.Threading.Thread.Sleep(5000);
    return 1;
}

当前回答

异步&等待简单的解释

简单的类比

一个人可能会等早班火车。这就是他们所做的一切,因为这是他们目前正在执行的主要任务。(同步编程(你通常做的事情!))

另一些人可能在等早班火车的时候,抽着烟,喝着咖啡。(异步编程)

什么是异步编程?

异步编程是指程序员选择在与主线程执行分开的线程上运行一些代码,然后在执行完成时通知主线程。

async关键字实际上做什么?

在方法名前加上async关键字,例如

async void DoSomething(){ . . .

允许程序员在调用异步任务时使用await关键字。这就是它所做的。

为什么这很重要?

在许多软件系统中,主线程专门用于与用户界面相关的操作。如果我正在运行一个非常复杂的递归算法,需要5秒才能在我的计算机上完成,但我在主线程(UI线程)上运行这个,当用户试图单击我的应用程序上的任何东西时,它将出现冻结,因为我的主线程已经排队,目前正在处理太多的操作。因此,主线程无法处理从鼠标点击到从按钮点击运行的方法。

什么时候使用Async和Await?

在不涉及用户界面的情况下,最好使用异步关键字。

假设你正在编写一个程序,允许用户在手机上画草图,但是每隔5秒它就会在互联网上查看天气。

我们应该等待呼叫,轮询每5秒呼叫一次网络以获取天气,因为应用程序的用户需要保持与移动触摸屏的交互以绘制漂亮的图片。

如何使用Async和Await

从上面的例子,下面是一些如何编写它的伪代码:

    //ASYNCHRONOUS
    //this is called using the await keyword every 5 seconds from a polling timer or something.

    async Task CheckWeather()
    {
        var weather = await GetWeather();
        //do something with the weather now you have it
    }

    async Task<WeatherResult> GetWeather()
    {

        var weatherJson = await CallToNetworkAddressToGetWeather();
        return deserializeJson<weatherJson>(weatherJson);
    }

    //SYNCHRONOUS
    //This method is called whenever the screen is pressed
    void ScreenPressed()
    {
        DrawSketchOnScreen();
    }

附加说明-更新

我忘了在我最初的笔记中提到,在c#中,你只能等待被包裹在任务中的方法。例如,你可以等待这个方法:

// awaiting this will return a string.
// calling this without await (synchronously) will result in a Task<string> object.
async Task<string> FetchHelloWorld() {..

你不能等待不是任务的方法,像这样:

async string FetchHelloWorld() {..

请随意查看Task类的源代码。

其他回答

也许我的见解是相关的。Async告诉编译器要特别对待一个函数,这个函数是可挂起/可恢复的,它以某种方式保存状态。Await暂停了一个功能,但也是一种执行纪律的方式,是限制性的;你需要指定你在等待什么,你不能无故挂起,这使得代码更有可读性,也许也更有效率。这就引出了另一个问题。为什么不等待多件事,为什么一次只等待一件事?我相信这是因为这样的模式已经建立起来了,而程序员们遵循的是最小惊讶的原则。这里存在着模棱两可的可能性:您是满足其中一个条件,还是希望所有条件都得到满足,也许只是其中一些?

除了其他答案,还有await (c#参考)

更具体地说,在包含的例子中,它解释了您的情况

下面的Windows窗体示例说明了await在 异步方法,WaitAsynchronouslyAsync。对比一下它的行为 方法使用waitsynchrontically的行为。没有等待 应用到任务的操作符,waitsynchronize同步运行 尽管在定义中使用了async修饰符,并且调用了 线程。睡在它的身体里。

private async void button1_Click(object sender, EventArgs e)
{
    // Call the method that runs asynchronously.
    string result = await WaitAsynchronouslyAsync();

    // Call the method that runs synchronously.
    //string result = await WaitSynchronously ();

    // Display the result.
    textBox1.Text += result;
}

// The following method runs asynchronously. The UI thread is not
// blocked during the delay. You can move or resize the Form1 window 
// while Task.Delay is running.
public async Task<string> WaitAsynchronouslyAsync()
{
    await Task.Delay(10000);
    return "Finished";
}

// The following method runs synchronously, despite the use of async.
// You cannot move or resize the Form1 window while Thread.Sleep
// is running because the UI thread is blocked.
public async Task<string> WaitSynchronously()
{
    // Add a using directive for System.Threading.
    Thread.Sleep(10000);
    return "Finished";
}

查看这个小提琴https://dotnetfiddle.net/VhZdLU(如果可能的话改进它),运行一个简单的控制台应用程序,在同一个程序中显示Task, Task. waitall (), async和await操作符的用法。

这个小提琴应该清楚你的执行周期的概念。

下面是示例代码

using System;
using System.Threading.Tasks;

public class Program
{
    public static void Main()
    {               
        var a = MyMethodAsync(); //Task started for Execution and immediately goes to Line 19 of the code. Cursor will come back as soon as await operator is met       
        Console.WriteLine("Cursor Moved to Next Line Without Waiting for MyMethodAsync() completion");
        Console.WriteLine("Now Waiting for Task to be Finished");       
        Task.WaitAll(a); //Now Waiting      
        Console.WriteLine("Exiting CommandLine");       
    }

    public static async Task MyMethodAsync()
    {
        Task<int> longRunningTask = LongRunningOperation();
        // independent work which doesn't need the result of LongRunningOperationAsync can be done here
        Console.WriteLine("Independent Works of now executes in MyMethodAsync()");
        //and now we call await on the task 
        int result = await longRunningTask;
        //use the result 
        Console.WriteLine("Result of LongRunningOperation() is " + result);
    }

    public static async Task<int> LongRunningOperation() // assume we return an int from this long running operation 
    {
        Console.WriteLine("LongRunningOperation() Started");
        await Task.Delay(2000); // 2 second delay
        Console.WriteLine("LongRunningOperation() Finished after 2 Seconds");
        return 1;
    }   

}

来自输出窗口的跟踪:

我认为你用System.Threading.Thread.Sleep选了一个不好的例子

异步任务的要点是让它在后台执行,而不锁定主线程,例如执行DownloadFileAsync

System.Threading.Thread.Sleep不是“正在完成”的事情,它只是休眠,因此你的下一行在5秒后到达……

阅读这篇文章,我认为它很好地解释了async和await概念:http://msdn.microsoft.com/en-us/library/vstudio/hh191443.aspx

public static void Main(string[] args)
{
    string result = DownloadContentAsync().Result;
    Console.ReadKey();
}

// You use the async keyword to mark a method for asynchronous operations.
// The "async" modifier simply starts synchronously the current thread. 
// What it does is enable the method to be split into multiple pieces.
// The boundaries of these pieces are marked with the await keyword.
public static async Task<string> DownloadContentAsync()// By convention, the method name ends with "Async
{
    using (HttpClient client = new HttpClient())
    {
        // When you use the await keyword, the compiler generates the code that checks if the asynchronous operation is finished.
        // If it is already finished, the method continues to run synchronously.
        // If not completed, the state machine will connect a continuation method that must be executed WHEN the Task is completed.


        // Http request example. 
        // (In this example I can set the milliseconds after "sleep=")
        String result = await client.GetStringAsync("http://httpstat.us/200?sleep=1000");

        Console.WriteLine(result);

        // After completing the result response, the state machine will continue to synchronously execute the other processes.


        return result;
    }
}