■ Task 클래스에서 반복 작업자를 사용하는 방법을 보여준다. (기능 개선)
▶ RepeatWorker.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 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 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 |
using System; using System.Threading; using System.Threading.Tasks; namespace TestProject { /// <summary> /// 작업 반복자 /// </summary> public class RepeatWorker : IDisposable { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field (Private) /// <summary> /// 취소 토큰 소스 /// </summary> private CancellationTokenSource cancellationTokenSource = null; /// <summary> /// 건너뛰기 시간 (단위 : 밀리초) /// </summary> private int skipTime; /// <summary> /// 건너뛰기 시간 범위 /// </summary> private TimeSpan skipTimeSpan; /// <summary> /// 휴지 시간 (단위 : 밀리초) /// </summary> private int sleepTime = 1000; /// <summary> /// 휴지 시간 범위 /// </summary> private TimeSpan sleepTimeSpan; /// <summary> /// 작업 액션 /// </summary> private Action<object> workAction = null; /// <summary> /// 작업 매개 변수 /// </summary> private object workParameter = null; /// <summary> /// 실행 여부 /// </summary> private bool isRunning = false; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 건너뛰기 시간 (단위 : 밀리초) - SkipTime /// <summary> /// 건너뛰기 시간 (단위 : 밀리초) /// </summary> public int SkipTime { get { return this.skipTime; } set { this.skipTime = value; this.skipTimeSpan = TimeSpan.FromMilliseconds(this.skipTime); } } #endregion #region 휴지 시간 (단위 : 밀리초) - SleepTime /// <summary> /// 휴지 시간 (단위 : 밀리초) /// </summary> public int SleepTime { get { return this.sleepTime; } set { this.sleepTime = value; this.sleepTimeSpan = TimeSpan.FromMilliseconds(this.sleepTime); } } #endregion #region 작업 액션 - WorkAction /// <summary> /// 작업 액션 /// </summary> public Action<object> WorkAction { get { return this.workAction; } set { this.workAction = value; } } #endregion #region 작업 매개 변수 - WorkParameter /// <summary> /// 작업 매개 변수 /// </summary> public object WorkParameter { get { return this.workParameter; } set { this.workParameter = value; } } #endregion #region 실행 여부 - IsRunning /// <summary> /// 실행 여부 /// </summary> public bool IsRunning { get { return this.isRunning; } } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - RepeatWorker() /// <summary> /// 생성자 /// </summary> public RepeatWorker() { } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 시작하기 - Start() /// <summary> /// 시작하기 /// </summary> public void Start() { this.cancellationTokenSource = new CancellationTokenSource(); _ = ExecuteWorkAsync(this.cancellationTokenSource.Token); } #endregion #region 중단하기 - Stop() /// <summary> /// 중단하기 /// </summary> public void Stop() { if(this.cancellationTokenSource != null) { this.cancellationTokenSource.Cancel(); this.cancellationTokenSource.Dispose(); this.cancellationTokenSource = null; } } #endregion #region 리소스 해제하기 - Dispose() /// <summary> /// 리소스 해제하기 /// </summary> public void Dispose() { Stop(); } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Private #region 비동기 작업 실행하기 - ExecuteWorkAsync() /// <summary> /// 비동기 작업 실행하기 /// </summary> /// <returns>태스크</returns> private Task ExecuteWorkAsync() { return Task.Run(()=> { this.workAction(this.workParameter); }); } #endregion #region 비동기 작업 실행하기 - ExecuteWorkAsync(cancellationToken) /// <summary> /// 비동기 작업 실행하기 /// </summary> /// <param name="cancellationToken">취소 토큰</param> /// <returns>태스크</returns> private async Task ExecuteWorkAsync(CancellationToken cancellationToken) { try { this.isRunning = true; await Task.Delay(this.skipTimeSpan, cancellationToken); while(true) { await ExecuteWorkAsync(); await Task.Delay(this.sleepTimeSpan, cancellationToken); } } catch(Exception) { } finally { this.isRunning = false; } } #endregion } } |
▶ MainForm.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 |
using System; using System.Threading; using System.Windows.Forms; namespace TestProject { /// <summary> /// 메인 폼 /// </summary> public partial class MainForm : Form { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 동기화 컨텍스트 /// </summary> private SynchronizationContext context; /// <summary> /// 반복 작업자 /// </summary> private RepeatWorker worker; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - MainForm() /// <summary> /// 생성자 /// </summary> public MainForm() { InitializeComponent(); this.context = SynchronizationContext.Current; this.worker = new RepeatWorker(); this.worker.SleepTime = 1000; this.worker.WorkParameter = "홍길동"; this.worker.WorkAction = (p) => { this.context.Send ( _ => { this.listBox.Items.Add($"{DateTime.Now.ToString("HH:mm:ss")} : {p}, {this.worker.IsRunning}"); }, null ); }; this.runButton.Click += runButton_Click; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Private #region 실행 버튼 클릭시 처리하기 - runButton_Click(sender, e) /// <summary> /// 실행 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void runButton_Click(object sender, EventArgs e) { if(this.runButton.Text == "실행") { this.runButton.Text = "중단"; this.worker.Start(); } else { this.runButton.Text = "실행"; this.worker.Stop(); Thread.Sleep(500); this.listBox.Items.Add($"{DateTime.Now.ToString("HH:mm:ss")} : {this.worker.WorkParameter}, {this.worker.IsRunning}"); } } #endregion } } |