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
정성태

... 31  32  33  34  35  36  37  38  39  40  41  42  43  [44]  45  ...
NoWriterDateCnt.TitleFile(s)
4783후배12/13/201619354MemoryStream에 관한 질문 입니다. [5]
4782김형민12/6/201618099[ C# 6.0 ] 126p 오타인가요? [6]
4781질문자11/29/201618286ms워드 저장 오류 [1]
4780최진11/28/201622844안녕 하세요 빌드 관련해서 질문드립니다 꾸벅 [4]
4779손니11/28/201619176안녕하세요 질문하다 드려도 될까요 [3]
4778김상호11/25/201618261재귀호출->비재귀호출 [2]파일 다운로드1
4777권오영11/12/201621308아래 질문 상세 소스전체입니다.. [3]
4776권오영11/11/201619052제가 이클립스를 공부중인데..이상한것을 찾았습니다.. [2]
4775이성환11/11/201622877안녕하세요. SnapsToDevicePixels 질문입니다. [5]파일 다운로드1
4774popo11/10/201619379.net SSL통신 관련 질문 드립니다. [1]
4773김상호11/4/201621052재귀함수 반복문 변환 [1]파일 다운로드1
4772자연인10/27/201622477hwpctrl을 사용하는 사이트에서 나와 브라우저를 종료하면 오류메세지가 나옵니다. [1]파일 다운로드1
4771문종훈10/18/201622286.net 소스 질문이 있습니다 [2]
4770누구게~...10/15/201619706세도나 [1]
4769spow...10/13/201617857올리시는 게시물에 '좋아요'를 선택할 수 있도록 해주세요 [3]
4768브라운10/11/201619623질문 하나만 드려도 될까요 [4]
4767암호군10/4/201625169c# aes 128 암복호화 관련 문의드립니다. [3]
4766김신철9/29/201619763Visual Studio 2015에서 .net 3.5로 c# 6.0 사용시 문제점에 대해서 궁금합니다. [1]
4765spow...9/23/201618765참조를 통해 속성의 값을 변경하고 싶을 때 우아한 코딩 방법이 있을까요? [2]
4764지현명9/22/201620655Visual Studio 2008 c#에서 추가된 솔류션의 디버깅이 안걸립니다. [2]파일 다운로드1
4763송기태9/20/201618869안녕하세요! 질문이 있어 문의드립니다! [1]파일 다운로드1
4762김신철9/20/201620056Visual Studio 2015 마이그레이션 후 빌드 및 에러 문제.. 도와주세요~ [2]
4761JH9/19/201620466WPF로 Viewbox 사용 시 폰트 크기 일정화 여부 [1]
4760초보9/18/201621918유닉스서버(HP)에서 C# 서버 프로그램 실행 가능 한지요? [1]
4759dev009/16/201623361Queue out of memory [3]
4758임기성9/12/201621847MS오피스 워드 64비트에서 32비트 COM개체 사용방법 문의 [2]
... 31  32  33  34  35  36  37  38  39  40  41  42  43  [44]  45  ...