根据我的理解,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;
}

当前回答

除了其他答案,还有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";
}

其他回答

下面是通过打开对话框读取excel文件的代码,然后使用async和等待运行异步代码,从excel逐行读取并绑定到网格

namespace EmailBillingRates
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            lblProcessing.Text = "";
        }

        private async void btnReadExcel_Click(object sender, EventArgs e)
        {
            string filename = OpenFileDialog();

            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(filename);
            Microsoft.Office.Interop.Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
            Microsoft.Office.Interop.Excel.Range xlRange = xlWorksheet.UsedRange;
            try
            {
                Task<int> longRunningTask = BindGrid(xlRange);
                int result = await longRunningTask;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
            finally
            {
                //cleanup  
               // GC.Collect();
                //GC.WaitForPendingFinalizers();

                //rule of thumb for releasing com objects:  
                //  never use two dots, all COM objects must be referenced and released individually  
                //  ex: [somthing].[something].[something] is bad  

                //release com objects to fully kill excel process from running in the background  
                Marshal.ReleaseComObject(xlRange);
                Marshal.ReleaseComObject(xlWorksheet);

                //close and release  
                xlWorkbook.Close();
                Marshal.ReleaseComObject(xlWorkbook);

                //quit and release  
                xlApp.Quit();
                Marshal.ReleaseComObject(xlApp);
            }

        }

        private void btnSendEmail_Click(object sender, EventArgs e)
        {

        }

        private string OpenFileDialog()
        {
            string filename = "";
            OpenFileDialog fdlg = new OpenFileDialog();
            fdlg.Title = "Excel File Dialog";
            fdlg.InitialDirectory = @"c:\";
            fdlg.Filter = "All files (*.*)|*.*|All files (*.*)|*.*";
            fdlg.FilterIndex = 2;
            fdlg.RestoreDirectory = true;
            if (fdlg.ShowDialog() == DialogResult.OK)
            {
                filename = fdlg.FileName;
            }
            return filename;
        }

        private async Task<int> BindGrid(Microsoft.Office.Interop.Excel.Range xlRange)
        {
            lblProcessing.Text = "Processing File.. Please wait";
            int rowCount = xlRange.Rows.Count;
            int colCount = xlRange.Columns.Count;

            // dt.Column = colCount;  
            dataGridView1.ColumnCount = colCount;
            dataGridView1.RowCount = rowCount;

            for (int i = 1; i <= rowCount; i++)
            {
                for (int j = 1; j <= colCount; j++)
                {
                    //write the value to the Grid  
                    if (xlRange.Cells[i, j] != null && xlRange.Cells[i, j].Value2 != null)
                    {
                         await Task.Delay(1);
                         dataGridView1.Rows[i - 1].Cells[j - 1].Value =  xlRange.Cells[i, j].Value2.ToString();
                    }

                }
            }
            lblProcessing.Text = "";
            return 0;
        }
    }

    internal class async
    {
    }
}

当使用async和await时,编译器在后台生成一个状态机。

下面是一个例子,我希望我能解释一些正在发生的高级细节:

public async Task MyMethodAsync()
{
    Task<int> longRunningTask = LongRunningOperationAsync();
    // independent work which doesn't need the result of LongRunningOperationAsync can be done here

    //and now we call await on the task 
    int result = await longRunningTask;
    //use the result 
    Console.WriteLine(result);
}

public async Task<int> LongRunningOperationAsync() // assume we return an int from this long running operation 
{
    await Task.Delay(1000); // 1 second delay
    return 1;
}

好的,这里发生了什么:

Task<int> longRunningTask = LongRunningOperationAsync();开始执行LongRunningOperation 独立的工作完成了,假设主线程(线程ID = 1),然后等待longRunningTask到达。 现在,如果longRunningTask还没有完成,它仍在运行,MyMethodAsync()将返回到它的调用方法,因此主线程不会被阻塞。当longRunningTask完成时,来自ThreadPool的线程(可以是任何线程)将返回到MyMethodAsync()之前的上下文中并继续执行(在这种情况下将结果打印到控制台)。

第二种情况是longRunningTask已经完成执行,结果可用。当到达await longRunningTask时,我们已经有了结果,所以代码将继续在同一线程上执行。(在本例中将结果打印到控制台)。当然,对于上面的例子,情况并非如此,其中涉及到Task.Delay(1000)。

我想对此发表我的意见,如果任何其他答案包含我将解释的内容,我很抱歉,我读了大部分,但没有找到它,但我可能错过了一些东西。

我看到了很多错误的概念和很多好的解释,只是想解释一下异步与并行编程的区别,我相信这会让事情更容易理解。

当你需要做长时间的计算,处理器密集的工作,你应该选择使用并行编程,如果可能的话,以优化核心的使用。这将打开一些线程并同时处理一些事情。

假设你有一个数字数组,想要对每一个数字进行一些昂贵的长计算。平行是你的朋友。

异步编程在不同的用例中使用。

当你在等待一些不依赖于你的处理器的事情时,它用来释放你的线程,例如IO(写入和读取磁盘),当你执行IO时,你的线程什么都不做,当你等待一个昂贵的查询结果从DB返回时也是一样。

异步方法在线程等待很长时间返回结果时释放线程。这个线程可以被应用程序的其他部分使用(例如,在web应用程序中,它可以处理其他请求),也可以返回操作系统用于其他用途。

当您的结果完成时,相同的线程(或另一个线程)将返回给您的应用程序以继续处理。

在像。net这样的多线程环境中,异步编程不是强制性的(但是个很好的实践),在web应用程序中,其他线程将响应新请求,但如果你是在像nodejs这样的单线程框架中,这是强制性的,因为你不能阻塞你唯一的线程,否则你将无法回答任何其他请求。

总而言之,长处理器密集型计算将从并行编程中受益更多,而不依赖于处理器的长等待时间,如IO或DB查询或对某些API的调用将从异步编程中受益更多。

这就是为什么Entity Framework有一个async api来保存、列表、查找等等…

记住async/await与wait或waitAll不同,上下文不同。Async/await释放线程,是异步编程。wait / waitAll阻塞所有线程(它们没有被释放)来强制并行上下文中的同步…不同的东西…

希望这对某些人有用…

根据我的理解,async和await所做的主要事情之一是使代码易于编写和阅读。

它们是为了让异步代码易于编写和阅读。

这和生成后台线程来执行长时间逻辑是一样的吗?

一点也不。

//我不明白为什么这个方法必须被标记为'async'。

async关键字启用await关键字。所以任何使用await的方法都必须被标记为async。

// DoSomethingAsync()方法在5秒休眠后到达该行。难道不应该立即到达吗?

不会,因为异步方法默认情况下不会在另一个线程上运行。

//是否在后台线程上执行?

No.


你可能会发现我的async/await介绍很有用。官方MSDN文档也非常好(尤其是TAP部分),异步团队还发布了一个很好的FAQ。

异步&等待简单的解释

简单的类比

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

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

什么是异步编程?

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

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类的源代码。