Apply your C# skills to real-world programming including asynchronous code, RESTful APIs, and unit testing.
Welcome to the world of asynchronous programming in C#! In this chapter, you'll learn how to write responsive, efficient applications using `async`, `await`, and `Task`. You'll also discover how to manage concurrency, cancellation, and error handling like a pro.
Asynchronous programming allows your application to perform multiple operations simultaneously. This is especially important for I/O-bound operations like file access, network requests, and database queries.
public async Task<string> GetMessage()
{
await Task.Delay(1000); // Simulate delay
return "Hello from the asynchronous world!";
}
Understand how `Task` works is crucial for mastering async programming. A `Task` can be in one of several states: Running, WaitingToRun, Canceled, or Completed.
Concurrency is about managing multiple operations at the same time. Parallelism is a specific implementation of concurrency where those operations run on multiple threads.
var task1 = DoWorkAsync();
var task2 = DoMoreWorkAsync();
await Task.WhenAll(task1, task2);
Use `CancellationToken` to gracefully cancel long-running operations. This is especially important for user-initiated tasks like file uploads or database queries.
public async Task DoWorkAsync(CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
// Perform work
await Task.Delay(100);
}
}
Async methods can throw exceptions just like synchronous ones. Use `try-catch` blocks to handle errors, but remember that exceptions thrown inside `await` expressions are caught in the surrounding `catch` block.
try
{
await DangerousOperationAsync();
}
catch (Exception ex)
{
// Handle exception
}
Welcome to the exciting world of working with Web APIs in C#! In this chapter, you'll learn how to both consume and create powerful web APIs using modern C# technologies. We'll cover everything from making HTTP requests to external services, to building your own RESTful APIs from scratch.
The HttpClient class is a powerful tool for making HTTP requests to external web services. It's designed to be both easy-to-use and highly customizable.
using System.Net.Http;
public async Task<string> GetWeatherForecastAsync()
{
var client = new HttpClient();
var response = await client.GetAsync("https://api.weather.com/forecast");
return await response.Content.ReadAsStringAsync();
}
Creating your own web APIs in C# is easier than ever thanks to the powerful ASP.NET Core framework. You'll use controllers, routing, and dependency injection to build robust APIs.
[ApiController]
[Route("api/[controller]")]
public class WeatherController : ControllerBase
{
[HttpGet]
public IActionResult GetForecast()
{
var forecast = new WeatherForecast
{
Temperature = 75,
Summary = "Sunny"
};
return Ok(forecast);
}
}
As you build more complex APIs, there are several important concepts to keep in mind:
Securing your APIs is absolutely critical. Here are some must-follow security practices:
Web APIs are the backbone of modern web applications. They power everything from mobile apps to single-page web applications. Here are some common use cases:
Congratulations! You've now learned the fundamentals of calling and creating web APIs in C#. To continue your learning journey, consider exploring these topics:
Welcome to our section on Unit Testing in C#! Writing tests for your code is an essential part of modern software development. It ensures your code works as expected, catches bugs early, and helps maintain the quality of your application.
When writing unit tests, we often want to test a component in isolation. This is where dependency injection comes into play. By injecting mock dependencies, we can control the behavior of external components during testing.
public class Calculator
{
private readonly ILogger<Calculator> _logger;
public Calculator(ILogger<Calculator> logger)
{
_logger = logger;
}
public int Add(int a, int b)
{
var result = a + b;
_logger.LogInformation("Added {a} and {b} to get {result}", a, b, result);
return result;
}
}
Moq is a popular mocking framework for .NET. It allows you to create mock implementations of interfaces and classes, which can be used in your unit tests.
[TestMethod]
public void Add_ValidInput_ReturnsCorrectResult()
{
// Create mock logger
var mockLogger = new Mock<ILogger<Calculator>>();
// Create calculator with mock logger
var calculator = new Calculator(mockLogger.Object);
// Test the add method
int result = calculator.Add(2, 3);
// Verify results and logging
Assert.AreEqual(5, result);
mockLogger.Verify(l => l.LogInformation(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>(), It.IsAny<int>()), Times.Once());
}
Question 1 of 15