它的優點有
- 可以回傳值
- 搭配 async await 優化對 I/O bound 任務的行為
- 語意改善
回傳值
Thread 是沒有回傳值這回事的,要靠存取一個外部變數來達成類似的功能,但 Task 可以直接如以下操作
static void Main(string[] args)
{
    FooAsync();
    Console.ReadLine();
}
private static async void FooAsync()
{
    string msg = await Task.Run(() =>
     {
         return "msg from task";
     });
    Console.WriteLine(msg);
}
await an I/O bound task
簡單來說 CPU bound 是消耗本機 CPU 與相關資源程度來決定運算效能的任務,相對的 I/O bound 是即使提升了上述資源供給也沒有直觀幫助的任務;比方 web service,其速度取決於 伺服器要多久才能吐回資料,無關你自身的運算資源。
標記方法為 async 搭配對 I/O 任務 await 可以迴避掉等待 output 占用 thread 的情況
static void Main(string[] args)
{
    FooAsync();
    Console.ReadLine();
}
private static async void FooAsync()
{
    string msg = await GetJson("https://jsonplaceholder.typicode.com/todos");
    Console.WriteLine(msg);
}
public static async Task GetJson(string url)
{
    var client = new HttpClient();
    return await client.GetStringAsync(url);
}
 
 
沒有留言:
張貼留言