Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)
(시리즈 글이 3개 있습니다.)
.NET Framework: 830. C# - 비동기 호출을 취소하는 CancellationToken의 간단한 예제 코드
; https://www.sysnet.pe.kr/2/0/11888

닷넷: 2218. C# - (예를 들어, Socket) 비동기 I/O에 대한 await 호출 시 CancellationToken을 이용한 취소
; https://www.sysnet.pe.kr/2/0/13561

닷넷: 2231. C# - ReceiveTimeout, SendTimeout이 적용되지 않는 Socket await 비동기 호출
; https://www.sysnet.pe.kr/2/0/13580




C# - (예를 들어, Socket) 비동기 I/O에 대한 await 호출 시 CancellationToken을 이용한 취소

예전에,

C# - 비동기 호출을 취소하는 CancellationToken의 간단한 예제 코드
; https://www.sysnet.pe.kr/2/0/11888

CancellationToken을 설명하면서, 사용자가 직접 구현하는 취소 동작을 설명했습니다. 그러니까, 그 코드가 시사하는 바는, "마법은 없다"입니다. ^^ 모든 건, 개발자가 지정해 준 대로 동작하는 것이므로 CancellationToken을 이용한 취소도 결국 개발자가 어떻게 그것을 처리하느냐에 따라 달라집니다.

이번 글에서는 그에 대한 사례를 들어봅니다.




그나저나, 혹시 커널 레벨에 전달된 비동기 I/O를 어떻게 취소할 수 있는지 생각해 보셨나요? 닷넷 개발만 했다면 짐작할 수 없을 텐데요, Win32 시절의 개발자라면 비동기 I/O 원칙에 따라 CancelIo, CancelIoEx 함수 호출로 이어졌을 거라는 짐작을 할 수 있을 것입니다.

달리 말하면, CancellationToken을 이용한 비동기 I/O 메서드에 대한 취소를 원한다면 CancelIo/CancelIoEx API를 호출해야 하지만, 이것 역시 개발자가 그렇게 구현했어야만 하는 것입니다. 제가 이렇게 말했으니, 아마도 닷넷 코드의 비동기 I/O 코드가 언제나 그런 식으로 동작하는 것은 아니라는 것을 눈치채셨을 것입니다. ^^

여기서는 그에 대한 사례로 TcpClient의 NetworkStream.WriteAsync 사용 예를 보겠습니다. 우선, Write 동작에 대한 테스트를 받아주는 서버를 다음과 같이 구현해 주고,

internal class Program
{
    static void Main(string[] args)
    {
        Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        IPEndPoint ep = new IPEndPoint(IPAddress.Any, 15000);
        socket.Bind(ep);
        socket.Listen(5);

        while (true)
        {
            Socket clntSocket = socket.Accept();
            Console.WriteLine($"Connected: {clntSocket.RemoteEndPoint}");
            ThreadPool.QueueUserWorkItem((arg) =>
            {
                while (true)
                {  
                    // 끊김만 감지
                    try
                    {
                        if (clntSocket.Poll(0, SelectMode.SelectRead))
                        {
                            byte[] buff = new byte[1];
                            if (clntSocket.Receive(buff, SocketFlags.Peek) == 0)
                            {
                                break;
                            }
                        }
                    }
                    catch 
                    {
                        break;
                    }

                    Thread.Sleep(1000);
                }
                Console.WriteLine($"Client disconnected: {clntSocket.RemoteEndPoint}");
                clntSocket.Close();
            });
        }
    }
}

클라이언트는, Send에서의 (일단은) blocking 테스트 여부를 위해 다음과 같이 만들어 보겠습니다.

internal class Program
{
    static void Main(string[] args)
    {
        Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        client.Connect("192.168.100.20", 15000);
        int length = client.SendBufferSize; // Windows 11의 경우 보통 65536

        long totalSent = 0;
        int count = 0;
        while (true)
        {
            byte[] buf = new byte[length];
            Console.WriteLine($"Sending: {buf.Length}");
            int sendLen = client.Send(buf, 0, buf.Length, SocketFlags.None); // 메서드 호출 후 곧바로 반환
            totalSent += sendLen;
            count++;
            Console.WriteLine($"[{count}] Sent: {buf.Length}, Total: {totalSent}");
        }

        // client.Close();
    }
}

/* 출력 결과:
Sending: 65536
[1] Sent: 65536, Total: 65536
Sending: 65536
...[생략]...
Sending: 65536
[49] Sent: 65536, Total: 3211264
Sending: 65536
[50] Sent: 65536, Total: 3276800
Sending: 65536
*/

테스트를 해보면, 3MB 정도에서 (대상 소켓에서 Receive를 하지 않으므로) 버퍼가 모두 차는 바람에 더 이상 Send를 하지 못하고 Send 호출에 blocking이 걸리는 것을 확인할 수 있습니다.

그럼, 이제 위의 예제를 비동기로 만들어 보면,

static async Task Main(string[] args)
{
    TcpClient client = new TcpClient();

    client.Connect("192.168.100.20", 15000);
    NetworkStream ns = client.GetStream();

    int length = client.SendBufferSize;

    long totalSent = 0;
    int count = 0;

    while (true)
    {
        byte[] buf = new byte[length];
        Console.WriteLine($"Sending: {buf.Length}");
        Task task = ns.WriteAsync(buf, 0, buf.Length);

        await task;

        totalSent += length;
        count++;
        Console.WriteLine($"[{count}] Sent: {buf.Length}, Total: {totalSent}");
    }

    // client.Close();
}

/* 출력 결과:
Sending: 65536
[1] Sent: 65536, Total: 65536
Sending: 65536
...[생략]...
Sending: 65536
[49] Sent: 65536, Total: 3211264
Sending: 65536
[50] Sent: 65536, Total: 3276800
Sending: 65536
*/

역시나 동일하게 3MB 송신 후 await에서 걸리는 것을 확인할 수 있습니다. 단지, 동기 버전과 다른 점이 있다면 위의 비동기 버전에서는 스레드의 blocking이 아닌, TCP Send가 완료되지 않아 await 이후의 분리된 코드 영역이 콜백에서 실행되지 않는 것입니다.




자, 이제 위의 비동기 호출에 대한 취소를 해볼 텐데요, 차이점을 알기 위해 .NET Framework과 .NET Core 환경으로 나눠서 실행할 것입니다. 우선, .NET Framework 프로젝트로 위의 코드에서 비동기 호출을 취소하기 위한 코드만 다음과 같이 살짝 추가해 줍니다.

CancellationTokenSource ct = new CancellationTokenSource();

ThreadPool.QueueUserWorkItem((arg) =>
{
    Thread.Sleep(5000); // 5초 후에, Cancel 호출
    ct.Cancel();
    Console.WriteLine("Cancel called!");
});

// ct.CancelAfter(5000);

while (true)
{
    byte[] buf = new byte[length];
    Console.WriteLine($"Sending: {buf.Length}");
    Task task = ns.WriteAsync(buf, 0, buf.Length, ct.Token);

    await task;

    totalSent += length;
    count++;
    Console.WriteLine($"[{count}] Sent: {buf.Length}, Total: {totalSent}");
}

실행해 보면, 화면에는 분명히 "Cancel called!" 문자열이 출력되지만 여전히 "await task;" 이후의 코드로는 나아가지 않습니다. (물론, 취소에 따른 예외 발생도 없습니다.) 하지만, 위의 코드를 그대로 .NET Core/5+ 환경, 여기서는 .NET 8 프로젝트에서 만들어 테스트하면 5초 후에 다음과 같은 출력이 나옵니다.

Cancel called!
Unhandled exception. System.OperationCanceledException: The operation was canceled.
   at System.Threading.CancellationToken.ThrowOperationCanceledException()
   at System.Threading.CancellationToken.ThrowIfCancellationRequested()
   at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.ThrowException(SocketError error, CancellationToken cancellationToken)
   at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.System.Threading.Tasks.Sources.IValueTaskSource.GetResult(Int16 token)
   at System.Threading.Tasks.ValueTask.ValueTaskSourceAsTask.<>c.<.cctor>b__4_0(Object state)
--- End of stack trace from previous location ---
   at ConsoleApp5.Program.Main(String[] args)
   at ConsoleApp5.Program.<Main>(String[] args)

보는 바와 같이, CancellationTokenSource.Cancel 호출은 WriteAsync 호출을 대기하던 비동기 작업을 (.NET Framework과는 달리) 취소했습니다.




그 둘 간의 차이는 도대체 뭘까요? 당연히 구현상의 차이가 있겠죠. ^^ 우선, .NET Framework의 NetworkStream.WriteAsync 코드는 그 상위의 Stream 타입에 있는 WriteAsync를 호출합니다.

// referencesource/mscorlib/system/io/stream.cs
// https://github.com/microsoft/referencesource/blob/master/mscorlib/system/io/stream.cs

[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public virtual Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
    // If cancellation was requested, bail early with an already completed task.
    // Otherwise, return a task that represents the Begin/End methods.
    return cancellationToken.IsCancellationRequested // CancellationToken 처리는 I/O 발생 전에만 체크
                ? Task.FromCancellation(cancellationToken)
                : BeginEndWriteAsync(buffer, offset, count); // .NET APM 비동기 호출의 Begin...과 End... 조합
}

// BeginEndWriteAsync 메서드는 CancellationToken 처리가 없음
private Task BeginEndWriteAsync(Byte[] buffer, Int32 offset, Int32 count)
{            
    return TaskFactory<VoidTaskResult>.FromAsyncTrim(
                this, new ReadWriteParameters { Buffer=buffer, Offset=offset, Count=count },
                (stream, args, callback, state) => stream.BeginWrite(args.Buffer, args.Offset, args.Count, callback, state), // cached by compiler
                (stream, asyncResult) => // cached by compiler
                {
                    stream.EndWrite(asyncResult);
                    return default(VoidTaskResult);
                });
}  

보는 바와 같이 WriteAsync 호출에 전달한 CancellationToken은 I/O 발생 전에만 한번 체크하고 이후 I/O 동작을 수행하는 BeginWrite로는 전달하지 않고 있습니다. 당연히, 이렇게 호출한 I/O는 이후 취소할 수 있는 방법이 없습니다.

반면, .NET 8의 WriteAsync는 Socket.SendAsyncForNetworkStream 메서드를 거쳐,

// NetworkStream.WriteAsync

public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
    ValidateBufferArguments(buffer, offset, count);
    ThrowIfDisposed();
    if (!CanWrite)
    {
        throw new InvalidOperationException(SR.net_readonlystream);
    }

    try
    {
        return _streamSocket.SendAsyncForNetworkStream(
            new ReadOnlyMemory<byte>(buffer, offset, count),
            SocketFlags.None,
            cancellationToken).AsTask();
    }
    catch (Exception exception) when (!(exception is OutOfMemoryException))
    {
        throw WrapException(SR.net_io_writefailure, exception);
    }
}

Socket.SendAsyncForNetworkStream -> AwaitableSocketAsyncEventArgs.SendAsyncForNetworkStream -> Socket.SendAsync -> SocketAsyncEventArgs.DoOperationSend를 거치면서 CancellationToken이 계속 전달되고,

// Socket
public partial class Socket
{
    // ...[생략]...

    internal ValueTask SendAsyncForNetworkStream(ReadOnlyMemory<byte> buffer, SocketFlags socketFlags, CancellationToken cancellationToken)
    {
        if (cancellationToken.IsCancellationRequested)
        {
            return ValueTask.FromCanceled(cancellationToken);
        }

        AwaitableSocketAsyncEventArgs saea =
            Interlocked.Exchange(ref _singleBufferSendEventArgs, null) ??
            new AwaitableSocketAsyncEventArgs(this, isReceiveForCaching: false);

        Debug.Assert(saea.BufferList == null);
        saea.SetBuffer(MemoryMarshal.AsMemory(buffer));
        saea.SocketFlags = socketFlags;
        saea.WrapExceptionsForNetworkStream = true;
        return saea.SendAsyncForNetworkStream(this, cancellationToken);
    }

    private bool SendAsync(SocketAsyncEventArgs e, CancellationToken cancellationToken)
    {
        ThrowIfDisposed();

        ArgumentNullException.ThrowIfNull(e);

        // Prepare for and make the native call.
        e.StartOperationCommon(this, SocketAsyncOperation.Send);
        SocketError socketError;
        try
        {
            socketError = e.DoOperationSend(_handle, cancellationToken);
        }
        catch
        {
            // Clear in-use flag on event args object.
            e.Complete();
            throw;
        }

        return socketError == SocketError.IOPending;
    }

    // ...[생략]...

    internal sealed class AwaitableSocketAsyncEventArgs : SocketAsyncEventArgs, IValueTaskSource, IValueTaskSource<int>, IValueTaskSource<Socket>, IValueTaskSource<SocketReceiveFromResult>, IValueTaskSource<SocketReceiveMessageFromResult>
    {
        // ...[생략]...

        public ValueTask SendAsyncForNetworkStream(Socket socket, CancellationToken cancellationToken)
        {
            if (socket.SendAsync(this, cancellationToken))
            {
                _cancellationToken = cancellationToken;
                return new ValueTask(this, _mrvtsc.Version);
            }

            SocketError error = SocketError;

            ReleaseForSyncCompletion();

            return error == SocketError.Success ?
                default :
                ValueTask.FromException(CreateException(error));
        }

        // ...[생략]...
    }
}

SocketAsyncEventArgs의 ProcessIOCPResult 내에서 마침내 cancellationToken에 대해 UnsafeRegister를 호출해 등록한 callback으로 CancelIoEx 호출을 하고 있습니다.

// dotnet/runtime/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.Windows.cs

internal unsafe SocketError DoOperationSend(SafeSocketHandle handle, CancellationToken cancellationToken) => _bufferList == null ?
    DoOperationSendSingleBuffer(handle, cancellationToken) :
    DoOperationSendMultiBuffer(handle);

internal unsafe SocketError DoOperationSendSingleBuffer(SafeSocketHandle handle, CancellationToken cancellationToken)
{
    Debug.Assert(_asyncCompletionOwnership == 0, $"Expected 0, got {_asyncCompletionOwnership}");

    fixed (byte* bufferPtr = &MemoryMarshal.GetReference(_buffer.Span))
    {
        NativeOverlapped* overlapped = AllocateNativeOverlapped();
        try
        {
            var wsaBuffer = new WSABuffer { Length = _count, Pointer = (IntPtr)(bufferPtr + _offset) };

            SocketError socketError = Interop.Winsock.WSASend(
                handle,
                &wsaBuffer,
                1,
                out int bytesTransferred,
                _socketFlags,
                overlapped,
                IntPtr.Zero);

            return ProcessIOCPResult(socketError == SocketError.Success, bytesTransferred, ref overlapped, _buffer, cancellationToken);
        }
        catch when (overlapped is not null)
        {
            FreeNativeOverlapped(ref overlapped);
            throw;
        }
    }
}

private unsafe SocketError ProcessIOCPResult(bool success, int bytesTransferred, ref NativeOverlapped* overlapped, Memory<byte> bufferToPin, CancellationToken cancellationToken)
{
    SocketError socketError = GetIOCPResult(success, ref overlapped);
    SocketFlags socketFlags = SocketFlags.None;

    if (socketError == SocketError.IOPending)
    {
        // Perform any required setup of the asynchronous operation.  Everything set up here needs to be undone in CompleteCore.CleanupIOCPResult.
        if (cancellationToken.CanBeCanceled)
        {
            Debug.Assert(_pendingOverlappedForCancellation == null);
            _pendingOverlappedForCancellation = overlapped;
            _registrationToCancelPendingIO = cancellationToken.UnsafeRegister(static s =>
            {
                // Try to cancel the I/O.  We ignore the return value (other than for logging), as cancellation
                // is opportunistic and we don't want to fail the operation because we couldn't cancel it.
                var thisRef = (SocketAsyncEventArgs)s!;
                SafeSocketHandle handle = thisRef._currentSocket!.SafeHandle;
                if (!handle.IsClosed)
                {
                    try
                    {
                        bool canceled = Interop.Kernel32.CancelIoEx(handle, thisRef._pendingOverlappedForCancellation);
                        if (NetEventSource.Log.IsEnabled())
                        {
                            NetEventSource.Info(thisRef, canceled ?
                                "Socket operation canceled." :
                                $"CancelIoEx failed with error '{Marshal.GetLastPInvokeError()}'.");
                        }
                    }
                    catch (ObjectDisposedException)
                    {
                        // Ignore errors resulting from the SafeHandle being closed concurrently.
                    }
                }
            }, this);
        }
        if (!bufferToPin.Equals(default))
        {
            _singleBufferHandle = bufferToPin.Pin();
        }

        // ...[생략]...
    }

    // ...[생략]...
    return socketError;
}

(뭔가 코드가 많지만) ^^ 동작 자체는 깔끔하게 취소가 됩니다.




약간의 수고를 곁들인다면 .NET Framework 버전에서도 Cancel 자체의 과정은 병합할 수 있습니다. 이에 대해서는 다음의 글에서 자세하게 소개하고 있는데요,

Is there a way I can cause a running method to stop immediately with a cts.Cancel();
; https://stackoverflow.com/questions/59243161/is-there-a-way-i-can-cause-a-running-method-to-stop-immediately-with-a-cts-cance/59267214#59267214

위의 내용을 이번 글에서 작성한 .NET Framework 코드에 병합한다면 다음과 같은 식으로 할 수 있습니다.

while (true)
{
    byte[] buf = new byte[length];
    Console.WriteLine($"Sending: {buf.Length}");
    Task task = ns.WriteAsync(buf, 0, buf.Length, ct.Token);

    var cancelable = new Task(() => { }, ct.Token);
    await Task.WhenAny(task, cancelable);

    if (ct.IsCancellationRequested) // 혹은 ct.Token.ThrowIfCancellationRequested(); 호출로 cancel 예외 발생
    {
        Console.WriteLine("Task cancelled!");
        break;
    }

    totalSent += length;
    count++;
    Console.WriteLine($"[{count}] Sent: {buf.Length}, Total: {totalSent}");
}

단지, 위와 같은 경우에는 WriteAsync 호출 시 커널로 넘어간 비동기 I/O에 대한 IRP가 취소된 것은 아니므로 buffer가 pinning 된 채로 살아있게 됩니다. 하지만, 현실적으로 위와 같은 경우에는 어차피 소켓을 정리하는 수순으로 넘어갈 것이므로 이후 Socket.Dispose 단계를 거치면 커널의 소켓 I/O도 해제될 것이므로 결국엔 버퍼가 정리됩니다.




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 3/18/2024]

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

비밀번호

댓글 작성자
 




[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13608정성태4/26/2024413닷넷: 2249. C# - 부모의 필드/프로퍼티에 대해 서로 다른 자식 클래스 간에 Reflection 접근이 동작할까요?파일 다운로드1
13607정성태4/25/2024412닷넷: 2248. C# - 인터페이스 타입의 다중 포인터를 인자로 갖는 C/C++ 함수 연동
13606정성태4/24/2024423닷넷: 2247. C# - tensorflow 연동 (MNIST 예제)파일 다운로드1
13605정성태4/23/2024645닷넷: 2246. C# - Python.NET을 이용한 파이썬 소스코드 연동파일 다운로드1
13604정성태4/22/2024675오류 유형: 901. Visual Studio - Unable to set the next statement. Set next statement cannot be used in '[Exception]' call stack frames.
13603정성태4/21/2024866닷넷: 2245. C# - IronPython을 이용한 파이썬 소스코드 연동파일 다운로드1
13602정성태4/20/2024931닷넷: 2244. C# - PCM 오디오 데이터를 연속(Streaming) 재생 (Windows Multimedia)파일 다운로드1
13601정성태4/19/2024962닷넷: 2243. C# - PCM 사운드 재생(NAudio)파일 다운로드1
13600정성태4/18/2024973닷넷: 2242. C# - 관리 스레드와 비관리 스레드
13599정성태4/17/2024936닷넷: 2241. C# - WAV 파일의 PCM 사운드 재생(Windows Multimedia)파일 다운로드1
13598정성태4/16/2024977닷넷: 2240. C# - WAV 파일 포맷 + LIST 헤더파일 다운로드2
13597정성태4/15/2024972닷넷: 2239. C# - WAV 파일의 PCM 데이터 생성 및 출력파일 다운로드1
13596정성태4/14/20241078닷넷: 2238. C# - WAV 기본 파일 포맷파일 다운로드1
13595정성태4/13/20241066닷넷: 2237. C# - Audio 장치 열기 (Windows Multimedia, NAudio)파일 다운로드1
13594정성태4/12/20241082닷넷: 2236. C# - Audio 장치 열람 (Windows Multimedia, NAudio)파일 다운로드1
13593정성태4/8/20241090닷넷: 2235. MSBuild - AccelerateBuildsInVisualStudio 옵션
13592정성태4/2/20241226C/C++: 165. CLion으로 만든 Rust Win32 DLL을 C#과 연동
13591정성태4/2/20241201닷넷: 2234. C# - WPF 응용 프로그램에 Blazor App 통합파일 다운로드1
13590정성태3/31/20241083Linux: 70. Python - uwsgi 응용 프로그램이 k8s 환경에서 OOM 발생하는 문제
13589정성태3/29/20241158닷넷: 2233. C# - 프로세스 CPU 사용량을 나타내는 성능 카운터와 Win32 API파일 다운로드1
13588정성태3/28/20241274닷넷: 2232. C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신 [2]파일 다운로드1
13587정성태3/27/20241360오류 유형: 900. Windows Update 오류 - 8024402C, 80070643
13586정성태3/27/20241532Windows: 263. Windows - 복구 파티션(Recovery Partition) 용량을 늘리는 방법
13585정성태3/26/20241497Windows: 262. PerformanceCounter의 InstanceName에 pid를 추가한 "Process V2"
13584정성태3/26/20241455개발 환경 구성: 708. Unity3D - C# Windows Forms / WPF Application에 통합하는 방법파일 다운로드1
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...