This runs work that returns the number 42 when done.
C Sharp (C#)
Task<int> task = Task.Run(() => {
return42;
});
This waits for the task to finish and gets the result 15.
C Sharp (C#)
int result = await Task.Run(() => 10 + 5);
Sample Program
This program shows how to run a task that does some work and waits for it. Then it runs a task that returns a number and prints that number.
C Sharp (C#)
using System;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
// Task without result
Task task = Task.Run(() => {
Console.WriteLine("Starting work...");
Task.Delay(1000).Wait(); // Simulate work
Console.WriteLine("Work done.");
});
await task; // Wait for task to finish// Task with result
Task<int> taskWithResult = Task.Run(() => {
Task.Delay(500).Wait(); // Simulate workreturn123;
});
int result = await taskWithResult;
Console.WriteLine($"Result from task: {result}");
}
}
OutputSuccess
Important Notes
Use await to wait for a Task or Task<T> to finish without blocking your program.
Task.Delay simulates waiting without blocking the thread.
Task<T> lets you get a value back from background work easily.
Summary
Task runs work without returning a value.
Task<T> runs work and returns a value of type T.
Use await to get results or wait for tasks to finish smoothly.
Practice
(1/5)
1. What is the main difference between Task and Task<T> in C#?
easy
A. Task does not return a value, Task<T> returns a value of type T.
B. Task runs synchronously, Task<T> runs asynchronously.
C. Task is used only for UI threads, Task<T> for background threads.
D. Task can return multiple values, Task<T> returns only one.
Solution
Step 1: Understand Task behavior
Task represents an asynchronous operation that does not return a result.
Step 2: Understand Task<T> behavior
Task<T> represents an asynchronous operation that returns a value of type T when it completes.
Final Answer:
Task does not return a value, Task<T> returns a value of type T. -> Option A
Quick Check:
Return value presence = Task does not return a value, Task<T> returns a value of type T. [OK]
Hint: Remember: Task = no result, Task<T> = returns result [OK]
Common Mistakes:
Thinking Task runs synchronously
Confusing Task<T> with multiple return values
Assuming Task is only for UI threads
2. Which of the following is the correct way to declare a Task<int> that returns the number 5 asynchronously?
easy
A. Task<int> t = Task.Run(() => 5);
B. Task<int> t = new Task<int>(5);
C. Task<int> t = Task<int>.Run(5);
D. Task<int> t = Task.Run<int>(5);
Solution
Step 1: Check correct Task<T> creation syntax
Use Task.Run(() => value) to create and start a task returning a value.
Step 2: Validate each option
Task<int> t = Task.Run(() => 5); uses Task.Run(() => 5), which is correct. Options A, B, and C use invalid constructors or methods.