A Task represents an asynchronous operation that will complete in the future. Task (no result) and Task<TResult> are the core types of the Task Parallel Library (TPL) and the foundation of async/await in .NET. What a Task is - A promise-like object with a status: Created, WaitingForActivation, Running, RanToCompletion, Faulted or Canceled. - It may represent I/O work (a database query, HTTP call) with no thread dedicated to it, or CPU work running on a thread-pool thread. - It carries the result (Task<T>.Result) or exception, which is rethrown when you await it. Creating and using Tasks // I/O-bound: returned by async APIs Task<string> page = httpClient.GetStringAsync(url); string html = await page; // CPU-bound: offload to the thread pool Task<int> primes = Task.Run(() => CountPrimes(1_000_000)); // Already-known results Task<int> cached = Task.FromResult(42); Task done = Task.CompletedTask; Coordinating Tasks - await Task.WhenAll(t1, t2): run concurrently and wait for all. - await Task.WhenAny(t1, timeout): first to finish. - Continuations: t.ContinueWith(...) exists but await is usually clearer. - Cancellation: pass a CancellationToken; cancelled tasks end in the Canceled state and throw OperationCanceledException. - TaskCompletionSource<T>: create a Task you complete manually — useful to wrap callback-based or event-based APIs. Task vs Thread - A Thread is an OS-level execution unit; creating many is expensive. - A Task is a higher-level abstraction scheduled on the thread pool (or not using a thread at all for I/O). Tasks are composable, support results, exceptions and cancellation. ValueTask - ValueTask<T> avoids allocation when results are often available synchronously (for example, from a cache). It must be awaited only once. Best practices - Prefer async/await over Wait(), Result and ContinueWith. - Do not use Task.Run inside ASP.NET Core request handlers just to "make code async". - Always observe Task exceptions (await them); unobserved faulted tasks hide errors. - Avoid Task.Factory.StartNew unless you need its advanced options (LongRunning, custom schedulers).
Ravindra Wadile · · 0 likes