[C# 윈폼] C# BackgroundWorker 쓰레드 사용 방법


안녕하세요.

 

오늘은 C# 윈폼에서 BackgroundWorker 쓰레드에 대해서 알아보고 어떻게 사용하는지 또한 예제를 통해서 알려 드리려고 합니다.


 

BackgroundWorker 클래스란?


-     BackgroundWorker 클래스는 별도의 쓰레드에게 어떠한 일들을 시키기 위해 사용하는 클래스 입니다.

-     윈폼으로 예를 들면 UI 쓰레드와는 별도로 BackgroundWorker 쓰레드를 이용하면 별도로 작업들 수행할 수 있습니다.

 

BackgroundWorker 이벤트 종류


1.   DoWorker 이벤트

-     실제 작업할 내용을 지정하는 이벤트

 

2.   ProgressChanged 이벤트

-     DoWorker의 진척 사항을 전달

 

3.   RunWorkerCompleted 이벤트

-     작업 완료 지정 이벤트

 

그럼 이제 위 내용을 토대로 BackgroundWorker 쓰레드 예제 코드를 작성해 보도록 하겠습니다.


예시는 "File Create" 버튼 컨트롤을 클릭하면 임의로 지정된 경로에 파일을 생성시키는 작업을 ProgressBar 컨트롤로 동시에 진척사항까지 보여주는 예제로 해당 소스코드를 작성해 보도록 하겠습니다.


빈 윈폼 프로젝트 및 컨트롤 배치



예제 코드


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

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.IO;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Windows.Forms;

 

namespace BackgroundWorkerTest

{

    public partial class Form1 : Form

    {

        //작업 쓰레드 객체 전역으로 선언

        BackgroundWorker _worker = null

 

        public Form1()

        {

            InitializeComponent();

 

            // Load 이벤트

            this.Load += FormLoad_Event;

 

            //버튼 클릭 이벤트

            uiBtn_Create.Click += uiBtn_Create_Click;

 

            // Close 이벤트

            this.FormClosing += FormClosing_Event;

        }

 

        /// <summary>

        ///  Load 이벤트

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        public void FormLoad_Event(object sender, EventArgs e)

        {

            //백그라운드 객체 생성  스레드 시작

            InitBackgroundWorker();

        }

 

        /// <summary>

        /// 버튼 클릭 이벤트 핸들러

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        public void uiBtn_Create_Click(object sender, EventArgs e)

        {

            //작업 쓰레드가 Busy(실행중이 아닌상태라면

            if(_worker.IsBusy != true)

            {

                //비동기로 실행

                _worker.RunWorkerAsync();

            }

        }

 

        /// <summary>

        /// 백그라운드 스레드 생성  이벤트 선언

        /// </summary>

        public void InitBackgroundWorker()

        {

            _worker = new BackgroundWorker();

            _worker.WorkerReportsProgress = true;

            _worker.WorkerSupportsCancellation = true;

            _worker.DoWork += new DoWorkEventHandler(Worker_DoWork);

            _worker.ProgressChanged += 

new ProgressChangedEventHandler(Worker_ProgressChanged);

            _worker.RunWorkerCompleted +=

 new RunWorkerCompletedEventHandler(Worker_RunWorkerComplete);

        }

 

        /// <summary>

        /// 작업 쓰레드가 실제로 하는 

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        public void Worker_DoWork(object sender, DoWorkEventArgs e)

        {

            string tmpDir = @"C:\Temp\Create_{0}";

            int cnt = 0;

            int pct = 0;

 

            try

            {

                for(int idx = 1; idx <= 10; idx++)

                {

                    //이미 파일이 있다면

                    if (Directory.Exists(tmpDir.Replace("{0}", idx.ToString())))

                    {

                        //해당 파일 지우고

                        Directory.Delete(tmpDir.Replace("{0}", idx.ToString()));

                    }

                    //다시 생성

                    Directory.CreateDirectory(tmpDir.Replace("{0}", idx.ToString()));

 

                    pct = ((++cnt * 100/ idx);

                    _worker.ReportProgress(pct);

                }

            }

            catch { }

        }

 

        /// <summary>

        /// Progress 리포트 - UI 쓰레드

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        public void Worker_ProgressChanged(object sender, ProgressChangedEventArgs e)

        {

            this.uiPrg_FileCreate.Value = e.ProgressPercentage;

        }

 

        /// <summary>

        /// 작업 완료 - UI 쓰레드

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        public void Worker_RunWorkerComplete(object sender, RunWorkerCompletedEventArgs e)

        {

            //Error 체크

            if(e.Error != null)

            {

                string msg = string.Format("Errpr : {0}", e.Error.Message);

                MessageBox.Show(msg);

                return;

            }

            else

            {

                string msg = string.Format("파일 생성 성공");

                MessageBox.Show(msg);

            }

        }

 

        /// <summary>

        /// 폼이 닫히면

        /// 실행중이던 BackGroundWorker 스레드 종료

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        public void FormClosing_Event(object sender, EventArgs e)

        {

            //_worker 객체가 생성된게 있다면

            if (_worker != null)

            {

                //해당 스레드 객체가 Busy 상태이면

                if (_worker.IsBusy)

                {

                    //스레드 취소

                    _worker.CancelAsync();

                }

            }

        }

    }

}

 

Colored by Color Scripter

cs


실행 결과




728x90

이 글을 공유하기

댓글

Designed by JB FACTORY