Computer/Tips
[c#] WORKING WITH ASYNCHRONOUS METHODS IN C#
창천(蒼天)
2020. 3. 31. 10:25
출처 : http://gigi.nullneuron.net/gigilabs/working-with-asynchronous-methods-in-c/
gigi.nullneuron.net
반환값 없는 경우
private async void Button_Click(object sender, RoutedEventArgs e)
{
await GetHtmlAsync();
}
private async Task GetHtmlAsync()
{
var baseAddress = new Uri("http://mta.com.mt");
using (var httpClient = new HttpClient() { BaseAddress = baseAddress })
{
var response = await httpClient.GetAsync("/");
var content = await response.Content.ReadAsStringAsync();
MessageBox.Show("Response arrived!", "Slow website");
}
}
반환값이 있는 경우
private async void Button_Click(object sender, RoutedEventArgs e)
{
string html = await GetHtmlAsync();
}
private async Task<string> GetHtmlAsync()
{
var baseAddress = new Uri("http://mta.com.mt");
using (var httpClient = new HttpClient() { BaseAddress = baseAddress })
{
var response = await httpClient.GetAsync("/");
var content = await response.Content.ReadAsStringAsync();
return content;
}
}
Summary
- Use async Task methods wherever you can.
- Use async void methods for event handlers, but beware the dangers even there.
- Use the –Async suffix in asynchronous method names to make them easily recognisable as awaitable.
- Use Task.CompletedTask and Task.FromResult() to satisfy asynchronous contracts with synchronous code.
- Asynchronous code in Main() has not been possible until recently. Use C# 7.1+ or a workaround to get this working.