C#

C# delegate 실 사용 예제 !!! (쓰레드에서 접근하는 UI 예제 포함)

sheepone 2021. 12. 23. 11:28
반응형

 

Class내 Thread에서 Form에 현재 시간 전달

 

Class에서 Form을 접근해야 할때가 있는데 이럴때 delegate 대리자를 이용하여 호출할수 있다.

 

delegate 선언을 한뒤에 이벤트를 delegate 형식으로 선언한뒤 해당 이벤트를 폼에서 연결 시켜 주면 된다.

 

예제 Class

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace WindowsFormsApp7
{
    class Class1
    {
        //델리게이트 선언
        public delegate void Button_Click(string _text); 
        //선언한 델리게이트로 이벤트 생성
        public event Button_Click button_click ;

        Thread MainThread; 

        public Class1()
        {
            //테스트를 위한 쓰레드
            MainThread = new Thread(new ThreadStart(Update));
            MainThread.Start();
        }

        public void Update()
        {
            Stopwatch sw = new Stopwatch();
            sw.Restart();
            while (true)
            {
                if(sw.ElapsedMilliseconds > 2000)
                {
                    sw.Restart();
                    //이벤트 호출
                    button_click(DateTime.Now.ToString());
                }
            }
        }
    }
}

 

예제 Form

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;

namespace WindowsFormsApp7
{
    public partial class Form1 : Form
    {
        Class1 class1 = new Class1();

        public Form1()
        {
            InitializeComponent();
            //클래스 이벤트에 연결
            class1.button_click += new Class1.Button_Click(Button_Click);
        }

        public void Button_Click(string _text)
        {
            //여기에 할일 추가
            if (listBox1.InvokeRequired)
            {
                listBox1.Invoke(new MethodInvoker(delegate () {
                    listBox1.Items.Add(_text);
                }));
            }
            else
            {
                listBox1.Items.Add(_text);
            }
        }
    }
}

리스트박스에 뿌려서 보여주다 보니 부득이 하게 인보크를 추가

 

예제파일

WindowsFormsApp7.zip
0.25MB

반응형