Avatar ·

How and when to use async and await in C#? Explain with examples

Hello everyone! I'm a beginner C# developer and I can't figure out async/await. I've read the documentation, but I still have questions.\n\nI have a WinForms application that loads data from a web server. When I call the download method, the interface freezes for a few seconds. Here's my current code:\n\n```csharp\nprivate void Button_Click(object sender, EventArgs e)\n{\n var data = DownloadData("https://api.example.com/data");\n textBox1.Text = data;\n}\n\nprivate string DownloadData(string url)\n{\n using (var client = new WebClient())\n {\n return client.DownloadString(url);\n }\n}\n```\n\nI've heard that async/await solves the UI freezing problem. But I don't understand:\n\n1. How to properly declare an async method? Do I always need to return Task?\n2. When to use