c# - 寻找指导以了解如何使用Async和Await进行异步编程

标签 c# asynchronous task-parallel-library async-await

我通过了一个msdn示例代码,其中在单击按钮时调用了一个函数,在调用了例程后又使用了Await关键字,而函数使用了async关键字。

private async void StartButton_Click(object sender, RoutedEventArgs e)
        {

            int contentLength = await AccessTheWebAsync();

            resultsTextBox.Text +=
                String.Format("\r\nLength of the downloaded string: {0}.\r\n", contentLength);
        }

async Task<int> AccessTheWebAsync()
        { 
            HttpClient client = new HttpClient();
            Task<string> getStringTask = client.GetStringAsync("http://msdn.microsoft.com");
            DoIndependentWork();
            string urlContents = await getStringTask;

            return urlContents.Length;
        }


        void DoIndependentWork()
        {
            resultsTextBox.Text += "Working . . . . . . .\r\n";
        }



调用AccessTheWebAsync时,将使用await关键字,这是什么意思?
当此函数AccessTheWebAsync()将被执行时,将调用DoIndependentWork()函数,我猜这里控件将一直等到该函数DoIndependentWork()完成。我对吗?


再次有另一个声明叫做

string urlContents = await getStringTask;


他们为什么在这里使用等待。如果我们不在这里使用await,那会发生什么?

请指导我了解其工作方式的代码。

最佳答案

这是有关异步/等待方法的简要说明。

异步方法:


调用者不一定要完全阻止异步执行
方法
可能的退货类型

void:“一劳永逸”
Task:允许等待异步方法的终止
Task<T>:允许等待终止并获得类型T的结果

没有ref或out参数用于异步方法
必须再次包含一个await =>否则编译警告


等待任务


等待TPL任务的终止
返回任务的结果(如果任务与
结果类型)
必须仅在异步方法中出现=>否则编译错误


异步方法部分是同步的,部分是异步的


调用者同步执行该方法,直到等待阻塞
之后,方法rest异步执行
异步等待机制
高效的




public async Task<int> GetSiteLengthAsync(string url) 
{  
    HttpClient client = new HttpClient();               <= Sync  
    Task<string> download1 = client.GetStringAsync(url); <= Sync  
    string site1 = await download1;   <= Async (Another thread)
    return site1.Length;              <= Async (Another thread)
}

关于c# - 寻找指导以了解如何使用Async和Await进行异步编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19929208/

相关文章:

javascript - 异步错误卡住网站

C#异步对象

c# - 主线程的 SynchronizationContext.Current 如何在 Windows 窗体应用程序中变为 null?

c# - Task.Delay 永远不会完成

c# - 如何使 System.Net.WebProxy 不绕过本地 url?

c# - 如何将二进制字符串转换为bytes[]数组?

c# - winforms中的两种方式数据绑定(bind),在基类中实现的Inotifypropertychanged

Angular 2在每个之后调用函数

c# - 使用 Parallel.ForEach() 进行长时间运行的进程

c# - 使用程序创建和编辑word文档