2018年8月19日 星期日

【C#】Task

Task 是抽象化後的緒操作類(from the thread pool)

它的優點有
  1. 可以回傳值
  2. 搭配 async await 優化對 I/O bound 任務的行為
  3. 語意改善

回傳值
Thread 是沒有回傳值這回事的,要靠存取一個外部變數來達成類似的功能,但 Task 可以直接如以下操作
  1. static void Main(string[] args)
  2. {
  3. FooAsync();
  4. Console.ReadLine();
  5. }
  6.  
  7. private static async void FooAsync()
  8. {
  9. string msg = await Task.Run(() =>
  10. {
  11. return "msg from task";
  12. });
  13. Console.WriteLine(msg);
  14. }

await  an I/O bound task
簡單來說 CPU bound 是消耗本機 CPU 與相關資源程度來決定運算效能的任務,相對的 I/O bound 是即使提升了上述資源供給也沒有直觀幫助的任務;比方 web service,其速度取決於 伺服器要多久才能吐回資料,無關你自身的運算資源。

標記方法為 async 搭配對 I/O 任務 await 可以迴避掉等待 output 占用 thread 的情況
  1. static void Main(string[] args)
  2. {
  3. FooAsync();
  4. Console.ReadLine();
  5. }
  6.  
  7. private static async void FooAsync()
  8. {
  9. string msg = await GetJson("https://jsonplaceholder.typicode.com/todos");
  10. Console.WriteLine(msg);
  11. }
  12.  
  13. public static async Task GetJson(string url)
  14. {
  15. var client = new HttpClient();
  16. return await client.GetStringAsync(url);
  17. }

沒有留言:

張貼留言