[C# 문법] C# async 비동기 메서드 반환값 받기

안녕하세요.

 

오늘은 C# 문법에서 async 키워드를 사용해 비동기 프로그램을 만들고 여기서 비동기 메서드 하나를 만들어서 비동기 메서드의 반환값을 받는 방법에 대해서 알려 드리려고 합니다.

 

앞서 async, await 키워드를 이용하여 비동기 프로그램을 만들었었는데요. 해당 프로그램을 이용하여 추가적으로 작업을 해보도록 하겠습니다.

 

먼저 UI 구성은 아래와 같이 구성하였고 WPF로 작업하였습니다.

 

UI 구성

UI Xaml 소스코드
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<Window x:Class="WpfTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfTest"
        mc:Ignorable="d"
        Title="MainWindow" Height="600" Width="400">
    <Border Padding="10">
        <StackPanel>
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="2*"/>
                    <ColumnDefinition Width="*"/>
                </Grid.ColumnDefinitions>
 
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto"/>
                    <RowDefinition Height="Auto"/>
                    <RowDefinition Height="*"/>
                </Grid.RowDefinitions>
 
                <TextBlock Grid.Column="0" Grid.Row="0" Text="비동기 프로그램 예제" FontWeight="Bold" Margin="0 10 0 0"/>
                <Button x:Name="uiBtn_Async" Click="uiBtn_Async_Click" Grid.Column="1" Grid.Row="0" Margin="10 10 10 10" Content="Start" />
 
                <TextBlock Grid.Column="0" Grid.Row="1" Text="결과물 출력" />
                <RichTextBox x:Name="uiRtb_Output" Height="500" Grid.ColumnSpan="2" Grid.Row="2" IsReadOnly="True" AcceptsReturn="True"
                     HorizontalAlignment="Stretch"
                     VerticalAlignment="Stretch"/>
            </Grid>
 
        </StackPanel>
 
    </Border>
</Window>
 
cs

 

예제 코드
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
 
namespace WpfTest
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        FlowDocument flowDoc = new FlowDocument();
 
        public MainWindow()
        {
            InitializeComponent();
        }
 
        /// <summary>
        /// 비동기 시작 버튼 클릭 이벤트
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiBtn_Async_Click(object sender, RoutedEventArgs e)
        {
            Start();
        }
 
        private async Task Start()
        {
            Task<string> task1 = FirstAsync();
            Task task2 = SecondAsync();
 
            DispatcherMethod("비동기 시작");
 
            await task1;
            await task2;
 
            DispatcherMethod("비동기 종료");
 
            string result = await task1;
 
            DispatcherMethod(result);
 
        }
 
        /// <summary>
        /// 첫 번째, 비동기 메서드 선언
        /// </summary>
        /// <returns></returns>
        private async Task<string> FirstAsync()
        {
            await Task.Run( () =>
            {
                for(int idx = 0; idx < 5; idx++)
                {
                    Thread.Sleep(500);
 
                    DispatcherMethod("FirstAsync");
                }
            });
 
            return "첫번째 메서드 결과값 반환";
        }
 
        /// <summary>
        /// 두 번째, 비동기 메서드 선언
        /// </summary>
        /// <returns></returns>
        private async Task SecondAsync()
        {
            await Task.Run( () =>
            {
                for(int idx = 0; idx < 5; idx++)
                {
                    Thread.Sleep(500);
 
                    DispatcherMethod("SecondAsync");
                }
            });
        }
 
        private void DispatcherMethod(string msg)
        {
            Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate
            {
                flowDoc.Blocks.Add(new Paragraph(new Run($"{msg}")));
                uiRtb_Output.Document = flowDoc;
            }));
        }
    }
}
 
cs

 

실행 결과

 

위와 같이 Task<string> 이라고 하여, 비동기 메서드의 반환값을 문자열로 받아서 출력까지 해보았습니다.

 

이런식으로 비동기 메서드의 반환값을 가져올 수 있습니다.

 

감사합니다.

728x90

이 글을 공유하기

댓글

Designed by JB FACTORY