블로그 이미지
Every unexpected event is a path to learning for you.

카테고리

분류 전체보기 (2731)
Unity3D (814)
Programming (474)
Server (33)
Unreal (4)
Gamebryo (56)
Tip & Tech (228)
협업 (57)
3DS Max (3)
Game (12)
Utility (136)
Etc (96)
Link (32)
Portfolio (19)
Subject (90)
iOS,OSX (51)
Android (14)
Linux (5)
잉여 프로젝트 (2)
게임이야기 (3)
Memories (20)
Interest (38)
Thinking (38)
한글 (30)
PaperCraft (5)
Animation (408)
Wallpaper (2)
재테크 (18)
Exercise (3)
나만의 맛집 (3)
냥이 (10)
육아 (16)
Total
Today
Yesterday
03-29 07:22

주의 : 자칫 폼을 죽일 수 있음. 14 - 5 - 8 일 작성한 Thread 예제 사용 가능 

thread 사용에는 form 내부의 control에 접근하기 어려운 점들이 있다. 

progress Bar 나 text Box 등 접근해서 처리했으면 하는 것들이 있는데 

이를 해결하기 위해 C#에 존재하는 것이 BackGroundWorker 이다. 

Thread 와 동일하게 Work, Complete 가 존재하며, 

특별히 progressChanged 라는 것을 통해서 

Progress Bar 를 좀 더 편하게 처리할 수 있다. 

  1. BackgroundWorker backgroundWorker1 = new BackgroundWorker();  
  2.   
  3. public Form1()  
  4. {  
  5.     InitializeComponent();  
  6.   
  7.     backgroundWorker1.DoWork += new DoWorkEventHandler(Work);  
  8.     backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(ProgressB);  
  9.     backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(CompleteWork);  
  10.   
  11.     // progress 사용 유무  
  12.     backgroundWorker1.WorkerReportsProgress = true;  
  13.   
  14.     progressBar1.Maximum = 100000;  
  15. }  



위 소스와 같이 BackGroundWorker 를 선언하고, Work(), ProgressB(), CompleteWork()를 각기 선언해준다. 

Work() 는 실제로 BackGround 상에서 수행해야 할 작업을 넣어두면 된다. 

  1. private void Work(object sender, DoWorkEventArgs e)  
  2. {  
  3.     for (int i = 0; i < 100000; i++)  
  4.     {  
  5.         backgroundWorker1.ReportProgress(i);  
  6.     }  
  7. }  



위는 ReportProgress 를 통해서 bar 를 움직이는 work 이다. 

  1. private void ForForFor(object sender, DoWorkEventArgs e)  
  2. {  
  3.     for (int i = 0; i < 100000; i++)  
  4.     {  
  5.         backgroundWorker1.ReportProgress(i);  
  6.     }  
  7. }  



ProgressChangedEvent 인 ProgressB 는 

  1. private void ProgressB(object sender, ProgressChangedEventArgs e)  
  2. {  
  3.     progressBar1.Value = e.ProgressPercentage;  
  4. }  



위와 같이 나타나며, backgroundWorker1.ReportProgress(i) 로 처리가 가능하다. 

마지막으로 CompleteWork() 이며 

  1. private void CompleteWork(object sender, RunWorkerCompletedEventArgs e)  
  2. {  
  3.     if (e.Cancelled == true)  
  4.     {  
  5.   
  6.     }  
  7.     else if (e.Error != null)  
  8.     {  
  9.   
  10.     }  
  11.     else  
  12.     {  
  13.   
  14.     }  
  15. }  



으로 나타낼 수 있다. Cancell 과 Error 등의 상황으로 예외처리가 가능하고 

마지막 else 는 정상적인 처리가 끝났을 때, 무언가 처리를 하고 싶을 때 하면 된다. 

BackGroundWorker를 시작하고 싶을 때는 

  1. private void button1_Click(object sender, EventArgs e)  
  2. {  
  3.     backgroundWorker1.RunWorkerAsync();  
  4. }  



RunWorkerAsync() 를 통해서 시작하면~ 끗.



출처 : http://onlyican.tistory.com/221

반응형
Posted by blueasa
, |