# Threading\_Tasks\_Task\_TResult

***

**1. Async File Reading**

```c#
// Read a file asynchronously and return its contents as a task.
Task<string> ReadFileAsync(string filePath)
{
    return Task.Run(() => File.ReadAllText(filePath));
}
```

**2. Async Database Query**

```c#
// Execute a database query asynchronously and return the result as a task.
Task<List<T>> QueryDatabaseAsync<T>(string query)
{
    // Create a new database connection.
    using (var connection = new SqlConnection("..."))
    {
        // Create a command to execute the query.
        SqlCommand command = new SqlCommand(query, connection);

        // Execute the query asynchronously.
        return command.ExecuteReaderAsync().ContinueWith(task =>
        {
            // Convert the results to a list of the specified type.
            var reader = task.Result;
            var resultList = new List<T>();
            while (reader.Read())
            {
                resultList.Add((T)reader["ColumnName"]);
            }
            return resultList;
        });
    }
}
```

**3. Async Web Request**

```c#
// Make an asynchronous web request and return the response body as a task.
Task<string> MakeWebRequestAsync(string url)
{
    // Create a web request.
    WebRequest request = WebRequest.Create(url);

    // Get a response asynchronously.
    return Task.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, null);
}
```

**4. Async Image Loading**

```c#
// Load an image asynchronously from a URL and return the image as a task.
Task<Image> LoadImageAsync(string url)
{
    // Create a web request.
    WebRequest request = WebRequest.Create(url);

    // Get a response asynchronously.
    return Task.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, null).ContinueWith(task =>
    {
        // Get the image from the response.
        Image image = Image.FromStream(task.Result.GetResponseStream());

        // Return the image as a task.
        return image;
    });
}
```

**5. Async Task Chaining**

```c#
// Execute a series of asynchronous tasks in sequence.
async Task<string> AsyncTaskChaining()
{
    // Execute the first task and store its result.
    string result1 = await Task.Run(() => "Task 1");

    // Execute the second task and store its result.
    string result2 = await Task.Run(() => "Task 2");

    // Return the combined results.
    return $"{result1} {result2}";
}
```

**6. Async Task Parallelism**

```c#
// Execute a series of asynchronous tasks in parallel.
async Task<int[]> AsyncTaskParallelism()
{
    // Create a list of tasks.
    var tasks = new List<Task<int>>();

    // Add tasks to the list.
    for (int i = 0; i < 10; i++)
    {
        tasks.Add(Task.Run(() => i));
    }

    // Execute the tasks in parallel and store their results.
    int[] results = await Task.WhenAll(tasks);

    // Return the results.
    return results;
}
```

**7. Async Task Cancellation**

```c#
// Execute an asynchronous task with cancellation support.
async Task AsyncTaskCancellation()
{
    // Create a cancellation token.
    CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();

    // Execute the task.
    try
    {
        await Task.Run(() =>
        {
            // Perform a long-running operation.
            for (int i = 0; i < 1000000; i++)
            {
                // Check for cancellation.
                cancellationTokenSource.Token.ThrowIfCancellationRequested();
            }
        }, cancellationTokenSource.Token);
    }
    catch (OperationCanceledException)
    {
        // The task was cancelled.
    }
    finally
    {
        // Dispose the cancellation token.
        cancellationTokenSource.Dispose();
    }
}
```

**8. Async Task with Progress Reporting**

```c#
// Execute an asynchronous task with progress reporting.
async Task AsyncTaskWithProgressReporting()
{
    // Create a progress reporter.
    IProgress<int> progressReporter = new Progress<int>(value => Console.Write(value));

    // Execute the task.
    await Task.Run(() =>
    {
        // Perform a long-running operation with progress reporting.
        for (int i = 0; i < 100; i++)
        {
            // Report progress.
            progressReporter.Report(i);
        }
    });
}
```

**9. Async Task Synchronization**

```c#
// Synchronize access to a shared resource using asynchronous tasks.
async Task AsyncTaskSynchronization()
{
    // Create a semaphore.
    SemaphoreSlim semaphore = new SemaphoreSlim(1);

    // Execute tasks.
    Task task1 = Task.Run(async () =>
    {
        // Acquire the semaphore.
        await semaphore.WaitAsync();
        try
        {
            // Access the shared resource.
            Console.WriteLine("Task 1 accessing shared resource");
        }
        finally
        {
            // Release the semaphore.
            semaphore.Release();
        }
    });

    Task task2 = Task.Run(async () =>
    {
        // Acquire the semaphore.
        await semaphore.WaitAsync();
        try
        {
            // Access the shared resource.
            Console.WriteLine("Task 2 accessing shared resource");
        }
        finally
        {
            // Release the semaphore.
            semaphore.Release();
        }
    });

    // Wait for tasks to complete.
    await Task.WhenAll(task1, task2);
}
```

**10. Async Lazy Loading**

```c#
// Implement lazy loading using asynchronous tasks.
class LazyLoader
{
    private Task<T> _task;
    private T _value;

    public T Value
    {
        get
        {
            // Check if the value has been loaded.
            if (_task == null)
            {
                // Create a task to load the value.
                _task = Task.Run(() => LoadValue());
            }

            // Wait for the task to complete and return the value.
            return _task.Result;
        }
    }

    private T LoadValue()
    {
        // Perform the operation to load the value.
        return (T)Activator.CreateInstance(typeof(T));
    }
}
```

**11. Async Event Handling**

```c#
// Handle an asynchronous event using a task.
class AsyncEventHandler
{
    public void HandleEvent(object sender, EventArgs e)
    {
        // Create a task to handle the event.
        Task task = Task.Run(() =>
        {
            // Perform the event handling logic.
            Console.WriteLine("Event handled asynchronously");
        });
    }
}
```

**12. Async LINQ Extension Method**

```c#
// Extend LINQ to support asynchronous operations.
public static async Task<TResult> AsyncWhere<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, Task<bool>> predicate, Func<TSource, TResult> selector)
{
    // Create a list to store the results.
    List<TResult> results = new List<TResult>();

    // Iterate over the source collection.
    foreach (TSource item in source)
    {
        // Check if the item matches the predicate.
        bool matches = await predicate(item);

        // If the item matches, add it to the results.
        if (matches)
        {
            results.Add(selector(item));
        }
    }

    // Return the results.
    return results;
}
```

**13. Async Unit Testing**

```c#
// Write asynchronous unit tests using tasks.
[TestMethod]
public async Task AsyncUnitTest()
{
    // Create a task to perform the test.
    var task = Task.Run(async () =>
    {
        // Perform the test logic.
        Assert.AreEqual(1, 1);
    });

    // Wait for the task to complete.
    await task;
}
```

**14. Async Background Processing**

```c#
// Perform background processing using asynchronous tasks.
public class BackgroundProcessor
{
    public void Process()
    {
        // Create a task to perform the background processing.
        Task task = Task.Run(async () =>
        {
            // Perform the processing logic.
            await Task.Delay(1000);
        });
    }
}
```

**15. Async Queue Processing**

```c#
// Implement an asynchronous queue processing system using tasks.
public class QueueProcessor
{
    private BlockingCollection<Task> _queue = new BlockingCollection<Task>();

    public void Start()
    {
        // Create a task to consume the queue.
        Task consumerTask = Task.Run(() =>
        {
            while (true)
            {
                // Take a task from the queue.
                Task task = _queue.Take();

                // Execute the task.
                task.Wait();
            }
        });
    }

    public void Enqueue(Task task)
    {
        // Add the task to the queue.
        _queue.Add(task);
    }
}
```

**16. Async Data Binding**

```c#
// Perform asynchronous data binding using tasks.
public class DataBinder
{
    private ObservableCollection<object> _data = new ObservableCollection<object>();

    public ObservableCollection<object> Data
    {
        get { return _data; }
    }

    public async Task LoadData()
    {
        // Create a task to load the data.
        var task = Task.Run(async () =>
        {
            // Load the data asynchronously.
            var data = await GetData();

            // Add the data to the collection.
            foreach (var item in data)
            {
                _data.Add(item);
            }
        });

        // Wait for the task to complete.
        await task;
    }

    private async Task<IEnumerable<object>> GetData()
    {
        // Perform the data fetching operation asynchronously.
        return await Task.FromResult(Enumerable.Range(1, 10));
    }
}
```

**17. Async Workflow**

```c#
// Implement an asynchronous workflow using tasks.
public class Workflow
{
    public async Task Run()
    {
        // Create a task to perform the first step.
        Task step1Task = Task.Run(async () =>
        {
            // Perform the first step.
            await Task.Delay(1000);
        });

        // Create a task to perform the second step.
        Task step2Task = Task.Run(async () =>
        {
            // Perform the second step.
            await Task.Delay(1000);
        });

        // Wait for both tasks to complete.
        await Task.WhenAll(step1Task, step2Task);

        // Perform the third step.
        Console.WriteLine("Workflow completed");
    }
}
```

**18. Async Data Validation**

```c#
// Perform asynchronous data validation using tasks.
public class DataValidator
{
    public async Task<bool> Validate(object data)
    {
        // Create a task to perform the validation.
        var task = Task.Run(async () =>
        {
            // Perform the validation asynchronously.
            var result = await ValidateData(data);

            // Return the validation result.
            return result;
        });

        // Wait for the task to complete and return the result.
        return await task;
    }

    private async Task<bool> ValidateData(object data)
    {
        // Perform the data validation operation asynchronously.
        return await Task.FromResult(true);
    }
}
```

**19. Async Error Handling**

```c#
// Handle errors in asynchronous tasks using try/catch.
public void AsyncErrorHandling()
{
    try
    {
        // Create a task.
        Task task = Task.Run(() =>
        {
            // Throw an exception.
            throw new Exception();
        });

        // Wait for the task to complete.
        task.Wait();
    }
    catch (Exception ex)
    {
        // Handle the exception.
        Console.WriteLine(ex.Message);
    }
}
```

**20. Async Custom Exception Handling**

```c#
// Handle custom exceptions in asynchronous tasks.
public void AsyncCustomExceptionHandling()
{
    try
    {
        // Create a task.
        Task task = Task.Run(() =>
        {
            // Throw a custom exception.
            throw new CustomException();
        });

        // Wait for the task to complete.
        task.Wait();
    }
    catch (CustomException ex)
    {
        // Handle the custom exception.
        Console.WriteLine(ex.Message);
    }
}

public class CustomException : Exception
{
    public CustomException() { }
    public CustomException(string message) : base(message) { }
}
```

**21. Async Exception Propagation**

```c#
// Propagate exceptions in asynchronous tasks.
public void AsyncExceptionPropagation()
{
    try
    {
        // Create a task.
        Task task = Task.Run(() =>
        {
            // Throw an exception.
            throw new Exception();
        });

        // Wait for the task to complete.
        task.Wait();
```
