Try   HackMD

C# Async Await 上課筆記

Asynchronous programming in C# Introduction

1. 名詞解釋:

  • Parellel programming: 一台電腦的任務同時在不同CPU的Core上執行
  • Asynchronous programming: 一台電腦的任務執行後即交付出去(ex.到資料庫查詢資料),釋放Thread的資源,讓Thread可以繼續處理其他任務

2. Async programming的好處:

  • Thread Pool: Server Thread pool中Thread的數量等同於Server的CPU core數。Thread會占用龐大的電腦資源,所以一台電腦擁有太多Thread是不利的。
  • 當User發起HTTP request到Server時,Server 會從Thread pool中找尋閒置的Thread來處理Request
  • 當一台Server接收到的任務太多(ex.太多Http request),Thread的數量不足以應付任務時,就需要使用Asynchronous programming,讓一條Thread上可進行多個任務
    Image Not Showing Possible Reasons
    • The image file may be corrupted
    • The server hosting the image is unavailable
    • The image path is incorrect
    • The image format is not supported
    Learn More →

Async、Await和 Task

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →
重點

  • Async method: 非同步方法執行後的回傳結果為一個Task。Thread將Task交付出去以釋放自身資源,Task會有Status(等待執行、執行中、完成、失敗等)、Result(撈回來的資料等)
  • 注意若用下列方式取得Task的Result是會阻擋CPU的資源的

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →
取得Result時阻擋CPU資源

    var line = File.ReadAllLineAsync("TextFile.txt").Result
  • 若想要不阻擋CPU的資源來取得Task的Result,只要在Async method前面加上Await即可

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →
取得Result時不阻擋CPU資源

    var line = await File.ReadAllLineAsync("TextFile.txt")
  • 使用Async Await釋放CPU資源,在等待Task完成的期間CPU就可以處理其他任務。例如:其他Http Request