프로그래밍/C#

[C#] 코루틴 (COROUTINE) (3)

갓똥 2020. 5. 5. 16:24
728x90
반응형

1. 코루틴 예제

using System;
using System.Collections;
using System.Collections.Generic;

class Program {
    // SUBROUTINE
    public static int Foo() {
        Console.WriteLine("1"); return 10;
        Console.WriteLine("2"); return 20;
        Console.WriteLine("3"); return 30;
        Console.WriteLine("4"); return 40;
        Console.WriteLine("5"); return 50;
    }
    
    static void Main() {
        int n1 = Foo();
        int n2 = Foo();
        Console.WriteLine($"{n1}, {n2}"); // 10, 10
    }
}

 

일반적인 코드이다.
코루틴이 아닌 일반 함수인데 1을 출력하고 10을 반환하고 2를 출력하고 20을 반환.. 5까지 한다.
하지만 일반함수이므로 호출 시 1을 출력하고 10을 반환하게 되면 밑의 코드는 실행이 되지 않는다.
그리고 함수를 다시 호출해도 중간부터가 아닌 처음부터 호출하게 되므로 1을 출력하고 10을 반환한다.
따라서 Main의 n1, n2를 출력해보면 둘 다 10이 나오는것을 볼 수 있다.
위의 코드를 코루틴으로 바꿔보자.
코루틴 메소드를 만드는 방법이 있는데 반환 타입과 방법을 맞추어야 한다.

 ① 코루틴 메소드 만드는 방법

 

using System;
using System.Collections;
using System.Collections.Generic;

class Program {
    // COROUTINE - 열거자 인터페이스 타입으로 반환하는 경우
    public static IEnumerator<int> Foo() {
        Console.WriteLine("1"); yield return 10;
        Console.WriteLine("2"); yield return 20;
        Console.WriteLine("3"); yield return 30;
        Console.WriteLine("4"); yield return 40;
        Console.WriteLine("5"); yield return 50;
    }
    
    static void Main() {
        // 코루틴 메소드 호출
        IEnumerator<int> e = Foo();
        
        e.MoveNext();
        int ret1 = e.Current;
        
        e.MoveNext();
        int ret2 = e.Current;
        
        Console.WriteLine($"{ret1}, {ret2}"); // 10, 20
    }
}

 

위는 열거자 인터페이스 타입으로 반환하는 경우
아래는 컬렉션 인터페이스 타입으로 반환하는 경우이다.
나중에 LINQ같은 것들이 컬렉션 인터페이스 타입을 이용한다.

 

using System;
using System.Collections;
using System.Collections.Generic;

class Program {
    // COROUTINE - 컬렉션 인터페이스 타입으로 반환하는 경우
    public static IEnumerable<int> Foo() {
        Console.WriteLine("1"); yield return 10;
        Console.WriteLine("2"); yield return 20;
        Console.WriteLine("3"); yield return 30;
        Console.WriteLine("4"); yield return 40;
        Console.WriteLine("5"); yield return 50;
    }
    
    static void Main() {
        // 코루틴 메소드 호출
        IEnumerable<int> c = Foo();
        IEnumerator<int> e = c.GetEnumerator();
        
        e.MoveNext();
        int ret1 = e.Current;
        
        e.MoveNext();
        int ret2 = e.Current;
        
        Console.WriteLine($"{ret1}, {ret2}"); // 10, 20
    }
}

 ② 코루틴 메소드 호출하는 방법

    => 메소드 호출 후 열거자 참조 얻기

    => 열거자.MoveNext()로 호출

    => 메소드가 yield return 한 값은 열거자.Current를 통해 얻을 수 있다.

728x90
반응형