Home 16. Callback
Post
Cancel

16. Callback

Delegate - Event - Callback

  • Callback이라는 키워드는 delegate할때,
    그 뒤 event할떄 같이 언급된다.
  • 찾으면 질문도 많고 답변도 많은데
    딱 이해됐다기보다 아 이런느낌이구나 정도.

What is Callback?

  • 일단 위키의 설명을 보면

    1
    2
    3
    4
    5
    6
    7
    
      프로그래밍에서 콜백(callback) 또는  
      콜애프터 함수(call-after function)는  
      다른 코드의 인수로서 넘겨주는  
      실행 가능한 코드를 말한다.  
      콜백을 넘겨받는 코드는  
      이 콜백을 필요에 따라 즉시 실행할 수도 있고,  
      아니면 나중에 실행할 수도 있다.
    

    라고한다.
    조금더 쉽게 하면
    “실행가능한코드”만 method로 바꾸면 된다.

  • 간단한 예

    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
    
      class Test4
      {
          public delegate void delegatecallback(int i);
          delegatecallback dc;
    
          public delegate void eventcallback(int _i, delegatecallback _delegatecallback);
          event eventcallback ec;
    
          public Test4()
          {
              dc += mtd_2;   
              mtd_1(0, dc);
    
              // ec += mtd_1;
              // ec(1, dc);
          }
    
    
          void mtd_1(int _i, delegatecallback _delegatecallback)
          {
              for (int i = _i; i < 5; i++)
              {
                  if (i%2 == 0)
                  {
                      _delegatecallback(i);
                  }
              }
          }
    
          void mtd_2(int i)
          {
              Console.WriteLine(i);
          }
      }
    
    • mtd_1은 parameter로 int, delegatecallback을 받는다
    • delegatecallback은 mtd_2가 연결 되어있다.
    • mtd_1은 실행 중 조건에 따라 delegatecallback을 호출하고
      그 결과 mtd_2가 실행된다.
  • 하나더..1
    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
    
      List<string> names = new List<string>();
      names.Add("Bruce");
      names.Add("Alfred");
      names.Add("Tim");
      names.Add("Richard");
    
      // Display the contents of the list using the Print method.
      names.ForEach(Print);
    
      // The following demonstrates the anonymous method feature of C#
      // to display the contents of the list to the console.
      names.ForEach(delegate(string name)
      {
              Console.WriteLine(name);
      });
    
      void Print(string s)
      {
              Console.WriteLine(s);
      }
    
      /* This code will produce output similar to the following:
      * Bruce
      * Alfred
      * Tim
      * Richard
      * Bruce
      * Alfred
      * Tim
      * Richard
      */
    

    ForEach의 정의는2

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    
      public void ForEach(Action<T> action) {
          if( action == null) {
              ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
          }
          Contract.EndContractBlock();
    
          int version = _version;
    
          for(int i = 0 ; i < _size; i++) {
              if (version != _version && BinaryCompatibility.TargetsAtLeast_Desktop_V4_5) {
                      break;
              }
              action(_items[i]);
          }
    
          if (version != _version && BinaryCompatibility.TargetsAtLeast_Desktop_V4_5)
              ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion);
      }
    
  • 일단, 쉽게보면 위와같은 형태가 callback인데

    처음 접할 때 이게 뭔소리지 싶은건
    “A=B”다 처럼 딱 떨어지는게 아니라
    일종의 패턴같은거라서 그런갑다.

  • 아무튼 C#에서는 delegate를 사용해 구현한다.
    • 방법은 delegate를 parameter로 넘져주는 방식.

      사실 이 전에 delegate에 대해 쓴 글에있는데
      “use delegate as parameter”의 내용

    • 그래서 delegate를 시작으로 저 셋이 자주 엮인것.

      • delegate : 근본
      • event : delegate의 특수한 형태
      • callback : parameter로 delegate를 이용한것.
  • 차피 딴설명 이해도 안되서 대충 이해가 되는 내용만 적어보면
    • parameter로 delegate를 넘겨 실제 method를 호출 가능하게 함.
    • 흐름상 직접 호출하는 method에
      “이것도 같이 해줘”느낌으로 던지는것처럼 보인다.

Why Callback???

  • 잘 모르겠음 이걸 정리하는게 이 글 목적이었다..

    예를들어 Linq의 경우 사용시
    가독성이 좋아지고,
    결과 데이터의 새 형식생성이 쉬운 등
    확연히 이점이 있어 보이는데

    이 경우는 좀 달라보임.
    아마 이게 delegate를 넘겨주는
    “패턴”이기때문으로 보임.
    아님 내 지식이 짧거나……

    다만, 내가 느끼기에
    delegate, event, callback등
    다시말해 delegate와 그 파생군은
    쓸때 안쓸때 차이점이라면
    코딩하는데 좀더 유연해지는것 같다.

  • 여기는 정리가 잘 안되서 중구난방 하다가 다 날림…
  • 그냥 느낌만 알고 넘어가고
    나중에 정리 가능해지면 수정
    관련 내용은 아래 읽어보는게 더 나을듯.

참고

This post is licensed under CC BY 4.0 by the author.

15. Delegate, Event

17. Tuple

Comments powered by Disqus.