Think of a café. The waiter takes a coffee order, hands it to the machine, and instead of waiting goes to another table. When the coffee is ready, they come back.
This is asynchronous work. While waiting for one task to finish, other work continues. It is essential for keeping a program responsive.
You are fetching data from a database. This might take 200ms. If you write it synchronously, the program freezes for 200ms — the user can't do anything.
If you write it asynchronously, the program keeps running and the operation completes when the data arrives.
// Senkron — program bekler
public string VeriGetir()
{
Thread.Sleep(2000); // 2 saniye bekle (program donar)
return "Veri geldi";
}
// Asenkron — program beklemez
public async Task<string> VeriGetirAsync()
{
await Task.Delay(2000); // 2 saniye bekle (program çalışmaya devam eder)
return "Veri geldi";
}
// Kullanım:
public async Task Calistir()
{
var veri = await VeriGetirAsync();
Console.WriteLine(veri);
}
Task represents the async operation itself. Methods that return a result use Task<T>, methods that don't return anything use Task.
// Sonuç döndüren async metot
public async Task<int> ToplamHesaplaAsync(int a, int b)
{
await Task.Delay(100);
return a + b;
}
// Sonuç döndürmeyen async metot
public async Task KaydetAsync(string veri)
{
await Task.Delay(100);
Console.WriteLine($"{veri} kaydedildi.");
}