Microsoft MVP성태의 닷넷 이야기
글쓴 사람
victor Jo (jys923 at gmail.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)

안녕하세요.

wpf 뷰모델에서 소켓 통신을 하고 있습니다.

별도의 스레드에서 소켓으로 데이터를 받고있습니다.
그 스레드에서 UI를 업데이트하려고 하니 DependencyObject와 같은 스레드에서 DependencySource를 만들어야 합니다 오류가 발생했습니다.

            await App.Current.Dispatcher.InvokeAsync(() =>
            {
                SrcImg = (BitmapImage)tmpImg;
            });

이런식으로 하면 된다는데 오류가 해결이 안되네요.

뷰모델 생성자에서
Task.Run(async () => await ReceiveDataAsync());

public async Task ReceiveDataAsync()
{
    try
    {
        NetworkStream stream = _client.GetStream();

        while (_client.Connected)
        {
            // 헤더를 읽어 데이터 크기를 가져옵니다.
            //byte[] headerBuffer = new byte[4];
            //await stream.ReadAsync(headerBuffer, 0, headerBuffer.Length);
            //int dataSize = BitConverter.ToInt32(headerBuffer, 0);
            int dataSize = 1048576;
            // 데이터를 받을 버퍼를 초기화합니다.
            byte[] buffer = new byte[dataSize];
            int totalBytesRead = 0;

            // 데이터를 전부 받을 때까지 반복해서 읽습니다.
            while (totalBytesRead < dataSize)
            {
                int bytesRead = await stream.ReadAsync(buffer, totalBytesRead, dataSize - totalBytesRead);
                if (bytesRead == 0)
                {
                    // 연결이 끊겼거나 EOF
                    throw new IOException("Connection closed prematurely.");
                }
                totalBytesRead += bytesRead;
            }

            Log.Information($"Total bytes read: {totalBytesRead}");
            Bitmap m_bmpRes = new Bitmap(512, 512, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            ByteArrToBitmap(buffer, m_bmpRes);
            string bmpFileName = String.Format($"{Utilities.GetCurrentUnixTimestampSeconds()}.bmp");
            m_bmpRes.Save(bmpFileName, ImageFormat.Bmp);
            // 데이터 수신 완료 후 이벤트를 통해 데이터 전달
            //OnDataReceived(buffer);
            ImageSource tmpImg = BitmapToImageSource(m_bmpRes);
            await App.Current.Dispatcher.InvokeAsync(() =>
            {
                SrcImg = (BitmapImage)tmpImg;
            });
        }
    }
    catch (Exception ex)
    {
        // 예외 처리 필요
        Log.Information($"수신 오류: {ex.Message}");
    }
}

https://github.com/jys923/ProcessAutomation/blob/master/SonoCap.MES.UI/ViewModels/TestViewModel.cs


[연관 글]






[최초 등록일: ]
[최종 수정일: 7/17/2024]


비밀번호

댓글 작성자
 



2024-07-17 08시27분
여러 잡다한 코드 떼시고 문제만 재현이 되는 프로젝트를 올려주세요. 아래의 글을 참고하시면 됩니다.

재현 가능한 최소한의 예제 프로젝트란?
; http://www.sysnet.pe.kr/2/0/11452
정성태
2024-07-18 09시14분
ImageSource를 InvokeAsync 안으로 넣어주세요.

await App.Current.Dispatcher.InvokeAsync(() =>
{
    ImageSource tmpImg = BitmapToImageSource(m_bmpRes);
    SrcImg = (BitmapImage)tmpImg;
});

ImageSource는 Animatable, Freezable, DependencyObject를 상속받는 개체이기 때문에 생성 자체를 다른 스레드에서 하면 안 됩니다.

WPF - 스레드에 종속되는 DependencyObject
; https://www.sysnet.pe.kr/2/0/13682
정성태

... 16  17  18  [19]  20  21  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
5487진우4/27/202113329C# 엑셀 자동화 성능 향상 문의 [2]
5486지나가던...4/26/202113115닷넷 구현 코드 관련 질문 [2]
5485이재원4/17/202113289교재 315페이지 내용 질문 [3]
5484Syong4/16/202117233윈폼 기반의 응용프로그램 dll 참조와 32,64bit 빌드 관련 문의 [4]
5483한예지 donator4/15/202112287익명 형식과 var 관계 질문 있습니다. [2]
5482질문4/13/202114242WPF를 위한 MVVM toolkit 선택과 관련한 문의드립니다. [4]
5480한예지 donator4/5/202115106GetHashCode 질문있습니다! [2]
5479한예지 donator4/4/202114006Equals를 닷넷에서 어떻게 구현했는지 보고 싶을 떄는 어떻게 해야 될까요? [2]
5478갑자기C#3/23/202116971C# Winform에서 TextBox없이 입력 받을 수 있나요? [7]
5477달팽이3/18/202113148c# 도형을 그린후 편집하는 방법이 궁금합니다. [2]파일 다운로드1
5475dimo...3/2/202114038POH가 .NET 5에 추가된 것으로 알고 있습니다. POH가 유용한 경우는 어떤 경우가 있을까요? [1]
5474Syong2/26/202113590사용자 지정 컨트롤 생성시 Invalidate, Update, Refresh의 차이점 [2]
5473한예지 donator2/25/202113023디자인 타임이 뭔지 궁금합니다!! [5]
5472dimo...2/24/202114443등록하지 않고 ocx를 사용하는 `키움`관련 포스팅을 따라가다 질문드립니다. [9]
5471남산2/21/202112920MarshalDirectiveException 에 대한 질문입니다. [1]
5470한예지 donator2/7/202112637yield 질문있습니다!! [2]
5469유호성2/6/202112505Parallel + Task.Run 동시 실행 환경에서 간헐적으로 Task.Run()에서 null이 리턴됩니다. [3]파일 다운로드1
5467hero...2/4/202113057실행 환경에 따른 Thread.Sleep 딜레이 차이 질문 [8]
5466pr1/29/202112914c# winform load시 작업표시줄에 뜨지 않는 현상을 겪으신적이 있으신가요? [4]파일 다운로드1
5465영귤1/28/202113074두 번째 await 부터는 스레드 개수만 늘어나는 것이 아닌가요 [1]
5464민우1/26/202113878C# 빌드시 코드 치환되는걸 확인하는 방법 문의 [2]
5463한예지 donator1/24/202114624Parameters.AddWithValue 와 Parameters.Add 의 차이점이 궁금합니다. [2]
5462C#초보1/22/202114763사용자 정의 메시지 전달이 가능한가요? [2]
5461한예지 donator1/22/202113800AsEnumerable() 메서드 질문 있습니다! [2]
5459한예지 donator1/21/202113071typeof와 GetType의 차이점 질문있습니다. [2]
5458진우1/20/202114292C# DataTable 에 SQL 쿼리문을 실행하는 방법 문의 (LINQ 사용하지 않고) [6]
... 16  17  18  [19]  20  21  22  23  24  25  26  27  28  29  30  ...