Study/C#

BackgroundWorker를 통해 조금 더 안전하게 이벤트 기반으로 비동기 처리를 진행하는 패턴 사용해보기 (RunWorkerAsync, IsBusy)

13.d_dk 2021. 10. 13. 19:38
728x90
반응형

BackgroundWorker를 통해 조금 더 안전하게 이벤트 기반으로 비동기 처리를 진행하는 패턴 사용해보기 (RunWorkerAsync, IsBusy)

  • BackgroundWorker를 통해 thread pool에서 worker thread를 할당받아 작업을 실행할 수 있음
  • 이를 사용하여 이벤트 기반으로 비동기 처리를 진행하는 패턴(event-based asynchronous pattern)을 구현할 수 있음
  • 이를 사용하기 위해서는 먼저 BackgroundWorker로부터 객체를 생성
  • 이후 DoWork 이벤트 핸들러를 통해 실제 작업할 내용을 지정
  • 마지막으로 RunWorkerAsync() 메서드를 호출하여 작업을 수행시킴

 

  • 여기서 RunWorkerAsync() 메서드로 동작되는 작업이 수행 중일 때, 다시 RunWorkerAsync() 메서드가 호출되는 경우 InvalidOperationException이 발생할 수 있음
  • 이를 안전하게 수행하기 위해 IsBusy 프로퍼티를 사용할 수 있음

 

  • 아래의 예시는 조금 억지스럽게 BackgroundWorker를 통한 비동기 처리를 구현한 코드
  • 여기서 IsBusy 프로퍼티를 확인하는 부분이 없는 경우 InvalidOperationException이 발생함을 확인할 수 있음
  • IsBusy로 RunWorkerAsync() 동작 여부를 확인하는 경우 안전하게 동작됨을 확인할 수 있음
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace ConsoleApp1
{
    using System;
    using System.ComponentModel;
    class Program
    {
        static void Main(string[] args)
        {
            // ref : https://www.csharpstudy.com/Threads/backgroundworker.aspx
            // ref : https://docs.microsoft.com/en-us/dotnet/api/system.componentmodel.backgroundworker.isbusy?view=net-5.0
            BackgroundWorkerTest bwt = new BackgroundWorkerTest();
 
            while(true)
            {
                bwt.Execute();
            }
 
            return;
        }
    }
 
    class BackgroundWorkerTest
    {
        private BackgroundWorker worker;
 
        public BackgroundWorkerTest()
        {
            worker = new BackgroundWorker();
            worker.DoWork += new DoWorkEventHandler(worker_DoWork);
        }
        ~BackgroundWorkerTest()
        {
            worker.DoWork -= new DoWorkEventHandler(worker_DoWork);
        }
 
        public void Execute()
        {
            Console.WriteLine("Execute");
 
            // InvalidOperationException 방지
            while (worker.IsBusy) { }
            // 쓰레드풀에서 작업쓰레드 시작
            worker.RunWorkerAsync();
        }
 
        // 작업쓰레드가 실행할 Task 메서드
        void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            //긴 처리 가정
            Console.WriteLine("Long running task");
        }
    }
}
cs

 

Reference

https://github.com/daegukdo/TIL/tree/master/02_C_sharp/023_BackgroundWorker

https://www.csharpstudy.com/Threads/backgroundworker.aspx

 

BackgroundWorker - C# 프로그래밍 배우기 (Learn C# Programming)

C# BackgroundWorker 클래스 BackgroundWorker 클래스는 쓰레드풀에서 작업 쓰레드(Worker Thread)를 할당 받아 작업을 실행하는 Wrapper 클래스이다. BackgroundWorker는 이벤트를 기반으로 비동기 처리를 진행하는

www.csharpstudy.com

https://docs.microsoft.com/en-us/dotnet/api/system.componentmodel.backgroundworker.isbusy?view=net-5.0 

 

BackgroundWorker.IsBusy Property (System.ComponentModel)

Gets a value indicating whether the BackgroundWorker is running an asynchronous operation.

docs.microsoft.com

 

반응형