본문 바로가기

C#

c# winform background worker 사용하기

 

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
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
 
namespace WinFormsApp2
{
    public partial class Form1 : Form
    {
        private BackgroundWorker worker;
        public Form1()
        {
            InitializeComponent();
            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_RunWorkerCompleted);
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            button1.Enabled = false;
            worker.RunWorkerAsync();
        }
 
        void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            string srcDir = @"C:\Users\statking\vtt_train\train\labels";
            string destDir = @"C:\Users\statking\vtt_train\train\labels_copy";
 
            DirectoryInfo di = new DirectoryInfo(srcDir);
            FileInfo[] fileInfos = di.GetFiles();
            int totalFiles = fileInfos.Length;
            int counter = 0;
            int pct = 0;
            foreach (var fi in fileInfos)
            {
                string destFile = Path.Combine(destDir, fi.Name);
                if (!File.Exists(destFile))
                    { File.Copy(fi.FullName, destFile); }
                pct = ((++counter * 100/ totalFiles);                
                worker.ReportProgress(pct);                
            }
        }
 
        void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.progressBar1.Value = e.ProgressPercentage;
            label1.Text = (e.ProgressPercentage).ToString() + "%만큼 실행되었습니다";
        }
 
        void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                label1.Text = e.Error.Message;
                MessageBox.Show(e.Error.Message, "Error");
                return;
            }
 
            label1.Text = "모든 파일을 성공적으로 복사하였습니다!!";
            button1.Enabled = true;
        }
    }
}
 
cs

 

'C#' 카테고리의 다른 글

c# winform timer  (0) 2021.11.07
c# winform backgroundworker 스레드 중단/재개하기 코드  (1) 2021.11.06
c# winform chart(only for .net framework)  (0) 2021.11.06
c# winform listview  (0) 2021.11.05
c# winform drag & drop  (0) 2021.11.05