2010년 5월 1일, 2막

[c#] WORKING WITH ASYNCHRONOUS METHODS IN C# 본문

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/

 

Working with Asynchronous Methods in C#

In yesterday’s article, “Motivation for async/await in C#”, we have seen why asynchronous programming is important. We have also seen basic usage of the await keyword, which requi…

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

  1. Use async Task methods wherever you can.
  2. Use async void methods for event handlers, but beware the dangers even there.
  3. Use the –Async suffix in asynchronous method names to make them easily recognisable as awaitable.
  4. Use Task.CompletedTask and Task.FromResult() to satisfy asynchronous contracts with synchronous code.
  5. Asynchronous code in Main() has not been possible until recently. Use C# 7.1+ or a workaround to get this working.

 

'Computer > Tips' 카테고리의 다른 글

[C#] 트레이 아이콘 적용  (0) 2020.07.19
Git 사용법 관련  (0) 2020.04.24
[c#] 시스템 트레이 프로그램 작성  (0) 2019.08.23
[mysql] datetime 날짜 검색  (0) 2019.08.07
[C#] 크로스 스레드와 Control.Invoke  (0) 2019.07.24