Microsoft MVP성태의 닷넷 이야기
닷넷: 2335. C# - 간단하게 구현해 보는 IValueTaskSource 예제 [링크 복사], [링크+제목 복사],
조회: 367
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일

C# - 간단하게 구현해 보는 IValueTaskSource 예제

마침 질문이 나왔으니, ^^

ValueTask를 multiple await 하지 말라는데
; https://www.sysnet.pe.kr/3/0/5970

이참에 IValueTaskSource 인터페이스에 대해 알아보도록 하겠습니다. 다행히 이에 대해 상세하게 설명한 글이 있어,

Task, Async Await, ValueTask, IValueTaskSource and how to keep your sanity in modern .NET world
; https://blog.scooletz.com/2018/05/14/task-async-await-valuetask-ivaluetasksource-and-how-to-keep-your-sanity-in-modern-net-world/

Implementing custom IValueTaskSource – async without allocations
; https://tooslowexception.com/implementing-custom-ivaluetasksource-async-without-allocations/

위의 글을 베껴 참고하여 보겠습니다. ^^




우선 Task 외에도, await 대상이 될 수 있는, 즉 awaitable type은 원한다면 사용자 정의할 수 있는데요, 이에 대해서는 전에 다뤘었습니다.

C# - await을 Task 타입이 아닌 사용자 정의 타입에 적용하는 방법
; https://www.sysnet.pe.kr/2/0/11456

그렇다면, 굳이 왜 새롭게 IValueTaskSource 인터페이스가 나온 걸까요?

public interface IValueTaskSource<TResult>
{
    ValueTaskSourceStatus GetStatus(short token);
    void OnCompleted(Action continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags);
    TResult GetResult(short token);
}

우선, ValueTask는 기존의 Task를 반환하는 메서드에서 비동기 동작을 수행하지 않는 경우에 한해 GC Heap 사용을 줄여주는 역할을 합니다. 예제를 간단하게 살펴보면 다음과 같은데요,

namespace ConsoleApp3;

internal class Program
{
    static async Task Main(string[] args)
    {
        await ThreadSleep(0);
        await ThreadSleep(1);
    }

    private static ValueTask ThreadSleep(int sleep)
    {
        if (sleep == 0)
        {
            return new ValueTask(); // 비동기 동작을 하지 않는 경우, GC Heap 사용을 피할 수 있음
        }

        // 비동기 동작을 수행해야 하는 경우, Task를 사용하게 되어 GC Heap 사용을 피할 수 없음
        return new ValueTask(Task.Delay(sleep));
    }
}

위의 구현을 위해 ValueTask는 2개의 생성자를 제공합니다.

public readonly struct ValueTask<TResult>
{
    public ValueTask(Task task); // 비동기 동작을 위해 Task를 감싼 생성자
    public ValueTask(TResult result); // 동기 반환을 위해 TResult를 감싼 생성자
}

문제는, 여전히 비동기로 수행해야 한다면 Task 인스턴스가 생성돼 GC Heap을 사용하게 된다는 겁니다. 그리고 .NET Core 2.1부터 이것조차도 최소화하고 싶어 만들어 놓은 것이 바로 IValueTaskSource입니다.

이러한 변화를 위해 ValueTask도 3번째 생성자를 하나 더 제공하는데요,

public readonly struct ValueTask<TResult>
{
    public ValueTask(IValueTaskSource<TResult> source, short token); // IValueTaskSource를 사용하기 위한 생성자
}

보는 바와 같이 Task를 사용하지 않는 유형으로 IValueTaskSource<TResult>를 구현한 개체를 요구하고 있습니다. 실제 사용 사례를 들어보면 더 이해가 쉽겠죠? ^^ 이를 위해 Thread.Sleep을 IValueTaskSource를 구현한 개체로 감싼 DelayTaskSource 클래스를 이렇게 만들어 봤습니다.

// 아래 코드는 "C# - async/await 그리고 스레드 (3) Task.Delay 재현" 글에서 다룬 것을 따릅니다.

public class DelayTaskSource : IValueTaskSource
{
    System.Threading.Timer? _timer;
    Action? _action;

    public DelayTaskSource(int milliSeconds)
    {
        _timer = new Timer(expiredCallback, null, milliSeconds, 0);
    }

    public void GetResult(short token)
    {
    }

    public ValueTaskSourceStatus GetStatus(short token)
    {
        return (_timer == null) ? ValueTaskSourceStatus.Succeeded : ValueTaskSourceStatus.Pending;
    }

    public void OnCompleted(Action<object?> continuation, object? state, short token, ValueTaskSourceOnCompletedFlags flags)
    {
        if (_timer == null)
        {
            continuation(state);
            return;
        }

        _action = () => { continuation(state); };
    }

    private void expiredCallback(object? state)
    {
        if (_timer != null)
        {
            _timer.Dispose();
            _timer = null;
        }

        if (_action != null)
        {
            _action.Invoke();
            _action = null;
        }
    }
}

요건을 만족했으니, 이제 저것을 사용한 ThreadSleep 메서드를 구현할 수 있습니다.

using System.Threading.Tasks;
using System.Threading.Tasks.Sources;

namespace ConsoleApp3;

internal class Program
{
    static async Task Main(string[] args)
    {
        Console.WriteLine($"[{DateTime.Now}] START");
        await ThreadSleep(0);

        Console.WriteLine($"[{DateTime.Now}] Sleep 1000");
        await ThreadSleep(1000);

        Console.WriteLine($"[{DateTime.Now}] End");
    }

    private static ValueTask ThreadSleep(int sleep)
    {
        if (sleep == 0)
        {
            return new ValueTask(); // Sleep이 0인 경우, GC Heap 사용을 피할 수 있음
        }

        // Sleep이 0이 아닌 경우, IValueTaskSource를 사용하여 Task 개체의 사용을 피할 수 있음
        // return new ValueTask(Task.Delay(sleep));
        return new ValueTask(new DelayTaskSource(sleep), 0);
    }
}

이 예제를 실행하면 대충 다음과 같은 결과가 나옵니다.

[오전 8:53:23] START
[오전 8:53:23] Sleep 1000
[오전 8:53:24] End

일단 시간 차가 생성된 것에 따라 동작은 의도한 대로 됐는데요, 다시 말해 비동기를 위한 제어 과정에 새롭게 IValueTaskSource 인터페이스를 구현한 개체가 참여할 수 있게 된 것입니다.




물론, 위의 예제는 결국 DelayTaskSource 참조 타입을 생성했기 때문에 GC Heap 사용을 피할 수 없습니다. 하지만, 해당 기능을 하는 인스턴스를 Pool에 담아두고 재사용한다면 어떨까요?

이전 예제에 Pool을 사용한다면 대충 이런 식으로 나올 것입니다.

using Microsoft.Extensions.ObjectPool;
using System.Threading.Tasks.Sources;

namespace ConsoleApp3;

internal class Program
{
    static async Task Main(string[] args)
    {
        Log("START");
        await ThreadSleep(0);

        Log("Sleep 1000");

        for (int i = 0; i < 5; i++)
        {
            Log($"Sleep #{i + 1}");
            await ThreadSleep(1000);
        }

        Log("Sleep End");
    }

    public static void Log(string msg)
    {
        Console.WriteLine($"[{DateTime.Now}, {Thread.CurrentThread.ManagedThreadId}] {msg}");
    }

    // Install-Package Microsoft.Extensions.ObjectPool
    static ObjectPool<DelayTaskSource> _pool = new DefaultObjectPool<DelayTaskSource>(new DefaultPooledObjectPolicy<DelayTaskSource>(), 10);

    private static ValueTask ThreadSleep(int sleep)
    {
        if (sleep == 0)
        {
            return new ValueTask();
        }

        // return new ValueTask(Task.Delay(sleep));
        // return new ValueTask(new DelayTaskSource(sleep), 0);

        DelayTaskSource delayTask = _pool.Get();
        delayTask.Delay(sleep, _pool);
        return new ValueTask(delayTask, 0);
    }
}

public class DelayTaskSource : IValueTaskSource
{
    System.Threading.Timer? _timer;
    Action? _action;
    ObjectPool<DelayTaskSource>? _pool;


    public DelayTaskSource()
    {
        Program.Log("DelayTaskSource created");
    }

    public DelayTaskSource(int milliSeconds)
    {
        _timer = new Timer(expiredCallback, null, milliSeconds, 0);
    }

    public void Delay(int milliSeconds, ObjectPool<DelayTaskSource> pool)
    {
        if (_timer != null)
        {
            _timer.Dispose();
        }

        _pool = pool;
        _timer = new System.Threading.Timer(expiredCallback, null, milliSeconds, 0);
    }

    public void GetResult(short token)
    {
    }

    public ValueTaskSourceStatus GetStatus(short token)
    {
        return (_timer == null) ? ValueTaskSourceStatus.Succeeded : ValueTaskSourceStatus.Pending;
    }

    public void OnCompleted(Action<object?> continuation, object? state, short token, ValueTaskSourceOnCompletedFlags flags)
    {
        if (_timer == null)
        {
            continuation(state);
            _pool?.Return(this);
            Program.Log("DelayTaskSource Return at OnCompleted");
            return;
        }

        _action = () => { continuation(state); };
    }

    private void expiredCallback(object? state)
    {
        if (_timer != null)
        {
            _timer.Dispose();
            _timer = null;
        }

        if (_action != null)
        {
            _action.Invoke();
            _action = null;
        }

        _pool?.Return(this);
        Program.Log("DelayTaskSource Return at expiredCallback");
    }
}

위의 프로그램을 실행하면 출력이 이렇게 나옵니다.

[오전 10:24:14, 1] START
[오전 10:24:14, 1] Sleep 1000
[오전 10:24:14, 1] Sleep #1
[오전 10:24:14, 1] DelayTaskSource created
[오전 10:24:15, 6] Sleep #2
[오전 10:24:15, 6] DelayTaskSource created
[오전 10:24:15, 6] DelayTaskSource Return at expiredCallback
[오전 10:24:16, 6] Sleep #3
[오전 10:24:16, 6] DelayTaskSource Return at expiredCallback
[오전 10:24:17, 6] Sleep #4
[오전 10:24:17, 6] DelayTaskSource Return at expiredCallback
[오전 10:24:18, 6] Sleep #5
[오전 10:24:18, 6] DelayTaskSource Return at expiredCallback
[오전 10:24:19, 6] Sleep End
[오전 10:24:19, 6] DelayTaskSource Return at expiredCallback

보는 바와 같이 DelayTaskSource 개체는 2개만 생성됐고 이후 재사용돼 GC Heap 사용을 최소화했습니다. 이런 식의 개선을 실제로 .NET BCL에 적용한 사례가 아래의 글에 나옵니다.

Understanding the Whys, Whats, and Whens of ValueTask
; https://devblogs.microsoft.com/dotnet/understanding-the-whys-whats-and-whens-of-valuetask/

Socket 타입의 ReceiveAsync/SendAsync 메서드에 적용해 성능을 높였다고 언급하는데요, 보통의 서버 프로그램이 receive/send 작업을 고속으로 수행하게 되는 것을 감안하면 이런 최적화는 상당히 유용했을 것으로 판단됩니다.

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




이 정도면 대충 IValueTaskSource 인터페이스가 나온 이유에 대해 이해가 되셨을 겁니다. ^^ 그렇긴 해도 (마이크로소프트가 아닌) 일반 개발자가 저 인터페이스를 구현할 일은 거의 없을 것입니다. 실제로 문서에서도 이렇게 언급하고 있는데요,

Implementing IValueTaskSource / IValueTaskSource
; https://devblogs.microsoft.com/dotnet/understanding-the-whys-whats-and-whens-of-valuetask/#implementing-ivaluetasksource-/-ivaluetasksource<t>

Most developers should never need to implement these interfaces. They’re also not particularly easy to implement.
...
To make this easier for developers that do want to do it, in .NET Core 3.0 we plan to introduce all of this logic encapsulated into a ManualResetValueTaskSourceCore<TResult> type, a struct that can be encapsulated into another object that implements IValueTaskSource<TResult> and/or IValueTaskSource, with that wrapper type simply delegating to the struct for the bulk of its implementation.


게다가 구현도 쉽지 않아 .NET Core 3.0부터 ManualResetValueTaskSourceCore<TResult> 구조체를 제공했다고 하니, 만약 필요하다면 가급적 저 타입을 활용하는 것이 권장됩니다.




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 6/12/2025]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 61  62  63  64  65  66  67  68  69  70  71  [72]  73  74  75  ...
NoWriterDateCnt.TitleFile(s)
12164정성태2/29/202020430오류 유형: 598. Surface Pro 6 - Windows Hello Face Software Device가 인식이 안 되는 문제
12163정성태2/27/202018710.NET Framework: 899. 익명 함수를 가리키는 delegate 필드에 대한 직렬화 문제
12162정성태2/26/202023231디버깅 기술: 166. C#에서 만든 COM 객체를 C/C++로 P/Invoke Interop 시 메모리 누수(Memory Leak) 발생 [6]파일 다운로드2
12161정성태2/26/202019057오류 유형: 597. manifest - The value "x64" of attribute "processorArchitecture" in element "assemblyIdentity" is invalid.
12160정성태2/26/202019313개발 환경 구성: 469. Reg-free COM 개체 사용을 위한 manifest 파일 생성 도구 - COMRegFreeManifest
12159정성태2/26/202015867오류 유형: 596. Visual Studio - The project needs to include ATL support
12158정성태2/25/202019066디버깅 기술: 165. C# - Marshal.GetIUnknownForObject/GetIDispatchForObject 사용 시 메모리 누수(Memory Leak) 발생파일 다운로드1
12157정성태2/25/202018565디버깅 기술: 164. C# - Marshal.GetNativeVariantForObject 사용 시 메모리 누수(Memory Leak) 발생 및 해결 방법파일 다운로드1
12156정성태2/25/202017092오류 유형: 595. LINK : warning LNK4098: defaultlib 'nafxcw.lib' conflicts with use of other libs; use /NODEFAULTLIB:library
12155정성태2/25/202016956오류 유형: 594. Warning NU1701 - This package may not be fully compatible with your project
12154정성태2/25/202016164오류 유형: 593. warning LNK4070: /OUT:... directive in .EXP differs from output filename
12153정성태2/23/202020611.NET Framework: 898. Trampoline을 이용한 후킹의 한계파일 다운로드1
12152정성태2/23/202019119.NET Framework: 897. 실행 시에 메서드 가로채기 - CLR Injection: Runtime Method Replacer 개선 - 세 번째 이야기(Trampoline 후킹)파일 다운로드1
12151정성태2/22/202020421.NET Framework: 896. C# - Win32 API를 Trampoline 기법을 이용해 C# 메서드로 가로채는 방법 - 두 번째 이야기 (원본 함수 호출)파일 다운로드1
12150정성태2/21/202020781.NET Framework: 895. C# - Win32 API를 Trampoline 기법을 이용해 C# 메서드로 가로채는 방법 [1]파일 다운로드1
12149정성태2/20/202018935.NET Framework: 894. eBEST C# XingAPI 래퍼 - 연속 조회 처리 방법 [1]
12148정성태2/19/202022185디버깅 기술: 163. x64 환경에서 구현하는 다양한 Trampoline 기법 [1]
12147정성태2/19/202019171디버깅 기술: 162. x86/x64의 기계어 코드 최대 길이
12146정성태2/18/202020034.NET Framework: 893. eBEST C# XingAPI 래퍼 - 로그인 처리파일 다운로드1
12145정성태2/18/202020452.NET Framework: 892. eBEST C# XingAPI 래퍼 - Sqlite 지원 추가파일 다운로드1
12144정성태2/13/202020629.NET Framework: 891. 실행 시에 메서드 가로채기 - CLR Injection: Runtime Method Replacer 개선 - 두 번째 이야기파일 다운로드1
12143정성태2/13/202016471.NET Framework: 890. 상황별 GetFunctionPointer 반환값 정리 - x64파일 다운로드1
12142정성태2/12/202019450.NET Framework: 889. C# 코드로 접근하는 MethodDesc, MethodTable파일 다운로드1
12141정성태2/10/202018334.NET Framework: 888. C# - ASP.NET Core 웹 응용 프로그램의 출력 가로채기 [2]파일 다운로드1
12140정성태2/10/202019128.NET Framework: 887. C# - ASP.NET 웹 응용 프로그램의 출력 가로채기파일 다운로드1
12139정성태2/9/202019764.NET Framework: 886. C# - Console 응용 프로그램에서 UI 스레드 구현 방법
... 61  62  63  64  65  66  67  68  69  70  71  [72]  73  74  75  ...