-
Delegate, Event, ActionC#/기초 2021. 12. 14. 17:10
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication42 { public delegate void MyEventHandler(string message); class Publisher { public event MyEventHandler Active; public void DoActive(int number) { if (number % 10 == 0) Active("Active!" + number); else Console.WriteLine(number); } } class Subscriber { static public void MyHandler(string message) { Console.WriteLine(message); } static void Main(string[] args) { Publisher publisher = new Publisher(); publisher.Active += new MyEventHandler(MyHandler); // 이벤트시 실행 할 메소드 대리자로 등록 for (int i = 1; i < 50; i++) publisher.DoActive(i); } } }
출처: https://blog.hexabrain.net/151C# 강좌 19편. 델리게이트와 이벤트(Delegates and Events)
1. 델리게이트(Delegate) 오늘은 델리게이트(Delegate)에 대해서 알아보려고 합니다. 델리게이트는 한마디로 말해서 대리자라고 말할 수 있습니다. 즉, 대신 일을 해주는 녀석이라고 할 수 있겠죠? 다
blog.hexabrain.net
출처:https://mandy8303.tistory.com/19
C# : Chapter - 12 델리게이트와 이벤트
델리게이트 델리게이트는 메소드 에 대한 참조이다. 델리게이트에 메소드의 주소를 할당한 후, 델리게이트를 호출하면 델리게이트가 메소드를 호출해준다. 한정자 delegate 반환형식 델리게이트
mandy8303.tistory.com
private void EventUpdateFrameData(int id, int[,] frame)
{ // 메서드를 매개변수로 전달 하도록 Action 대리자 사용
// Invoke는 다른 스레드에서 직접 접근할 수 없는 윈폼 컨트롤 작업에 대해
// Invoke를 통해 작업 자체를 위임하여 MainThread가 해당 작업을 실행하게 한다.
// Invoke 동기 실행, BeginInvoke 비동기 실행
imgThermal.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.ApplicationIdle, new Action(
delegate ()
{
UpdateFrameData(id, frame);
}));
// new Aciton(반환값 없는 대리자 메소드)
}==========================================================
public class A { public delegate void DeleEventHandler(int a, string b); public event DeleEventHandler EventHandler; EventHandler?.Invoke(4, "문자열"); // 이벤트 발생 // B class B메소드 실행, C class C메소드 실행 ... } public class B { eventB = new A(); eventB.EventHandler += new A.DeleEventHandler(B메소드) public void B메소드(int a, string b) { // } ... } public class C { eventC = new A(); eventC.EventHandler += new A.DeleEventHandler(C메소드) public void C메소드(int a, string b) { // } }
by KIS
delegate를 통한 event사용의 장점
1. 이벤트는 개별적인 구독자 클래스 자체를 참조할 필요가 없다. (등록된 함수 주소만 관리)
2. 이벤트에 추가 된 함수끼리도 연결성이 없기 때문에 서로 영향을 미치지 않아 오류 위험이 적다.
3. 특정 상황(이벤트)에 발생할 함수들의 추가, 삭제를 통한 수정 및 관리가 간편하다. (특히 유동적일때)
delegate를 통한 event사용의 단점
1. 이벤트 이름 수정 시 함수가 등록 된 클래스에서 모두 수정해 주어야 한다.
2. 이벤트 클래스 내에서 어떤 함수들이 이벤트에 등록되어 있는지 직관적으로 알수는 없다.
[출처] [C#] delegate (대리자)와 event (이벤트)|작성자 두야
사(社)사(私)로운 블로그 '◡'✿ : 네이버 블로그
당신의 모든 기록을 담는 공간
blog.naver.com
728x90'C# > 기초' 카테고리의 다른 글
[C#]LINQ (0) 2022.02.21 [C#]문법 (0) 2022.02.18 WritePixels (0) 2021.12.24 [C#]WPF Serial Port (0) 2021.12.21 [C#] ??, ?. 연산자 ( Nullable) Null 널 (0) 2021.12.16 댓글