Skip to content

Instantly share code, notes, and snippets.

@1saeedsalehi
Created January 2, 2025 12:09
Show Gist options
  • Save 1saeedsalehi/bba58ab99a11980ea5b46020686f5c24 to your computer and use it in GitHub Desktop.
Save 1saeedsalehi/bba58ab99a11980ea5b46020686f5c24 to your computer and use it in GitHub Desktop.
Async / Await Example
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
public class Program
{
private record Temprature(string Source, double Temperature);
//Register at OpenWeatherMap and get your API key.
private const string ApiKey = "YOUR_API_KEY";
private static readonly HttpClient HttpClient = new();
private static async Task Main(string[] args)
{
Console.WriteLine("Fetching weather temperatures from multiple sources...\n");
// Define tasks for different weather sources
List<Task<Temprature>> weatherTasks = new()
{
GetWeatherFromSourceAAsync(),
GetWeatherFromSourceBAsync(),
GetWeatherFromSourceCAsync(),
GetRealWeatherFromOpenWeatherMapAsync("New York") // Real weather source
};
// Example 1: Wait for all sources to complete
Console.WriteLine("Waiting for all sources to complete:\n");
var allResults = await Task.WhenAll(weatherTasks);
foreach (var result in allResults)
{
Console.WriteLine($"Source: {result.Source}, Temperature: {result.Temperature}°C");
}
// Example 2: Process the first result that completes
Console.WriteLine("\nWaiting for the first source to complete:\n");
var firstResult = await Task.WhenAny(weatherTasks);
var completedResult = await firstResult; // Await the completed task
Console.WriteLine($"Source: {completedResult.Source}, Temperature: {completedResult.Temperature}°C\n");
Console.WriteLine("Done!");
}
// Simulate getting weather from Source A
private static async Task<Temprature> GetWeatherFromSourceAAsync()
{
await Task.Delay(2000); // Simulate network delay
return new Temprature("Source A", 25.3);
}
// Simulate getting weather from Source B
private static async Task<Temprature> GetWeatherFromSourceBAsync()
{
await Task.Delay(1000); // Simulate network delay
return new Temprature("Source B", 26.1);
}
// Simulate getting weather from Source C
private static async Task<Temprature> GetWeatherFromSourceCAsync()
{
await Task.Delay(1500); // Simulate network delay
return new Temprature("Source C", 24.8);
}
// Real weather source using OpenWeatherMap API
static async Task<Temprature> GetRealWeatherFromOpenWeatherMapAsync(string city)
{
var url = $"https://api.openweathermap.org/data/2.5/weather?q={city}&units=metric&appid={ApiKey}";
try
{
var response = await HttpClient.GetAsync(url);
response.EnsureSuccessStatusCode();
var json = await response.Content.ReadAsStringAsync();
using var doc = JsonDocument.Parse(json);
var temperature = doc.RootElement.GetProperty("main").GetProperty("temp").GetDouble();
return new Temprature(city, temperature);
}
catch (Exception ex)
{
Console.WriteLine($"Error fetching weather for {city}: {ex.Message}");
return new Temprature(city, double.NaN);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment