Bir kafe düşün. Garson kahve siparişini alır, makineye verir ve beklemek yerine diğer masaya gider. Kahve hazır olunca geri döner.
Bu asenkron çalışmadır. Bir işin bitmesini beklerken başka iş yapılır. Programın donmaması, kullanıcıya yanıt vermeye devam etmesi için şarttır.
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.
Veritabanından veri çekiyorsun. Bu işlem 200ms sürebilir. Senkron yazarsan program bu 200ms boyunca donar — kullanıcı hiçbir şey yapamaz.
Asenkron yazarsan program çalışmaya devam eder, veri gelince işlem tamamlanır.
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 asenkron bir işlemin kendisini temsil eder. Sonuç döndüren metotlar Task<T>, döndürmeyenler Task kullanır.
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.");
}