Understanding C# async / await 第3章
Understanding C# async / await 第1章原文地址
Understanding C# async / await 第2章原文地址
Understanding C# async / await 第3章原文地址
以下是基于你提供的内容的总结和解读,保留示例代码和关键细节:
理解 C# 的 async / await (3):运行时上下文 1. 概述 在前两篇文章中,我们探讨了 async 和 await 的编译过程和 Awaitable-Awaiter 模式。本文将深入探讨 await 在运行时的上下文处理机制,特别是如何通过 ExecutionContext 和 SynchronizationContext 解决跨线程问题。
2. 跨线程问题 在 WPF 应用程序中,以下代码可以正常工作:
this.Button.Click += async (sender, e) => { string html = await new WebClient().DownloadStringTaskAsync("https://weblogs.asp.net/dixin"); this.TextBox.Text = html; }; 但如果将其改写为 Task.ContinueWith() 的回调形式:
this.Button.Click += (sender, e) => { new WebClient().