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

... 61  [62]  63  64  65  66  67  68  69  70  71  72  73  74  75  ...
NoWriterDateCnt.TitleFile(s)
1093이지수10/6/201219205vbs [1]
1092김성수9/20/201220455안녕하세요? MS Windows server 2008 R2 에서 IIS7 의 SSL 설정시에 에러 해결좀 도와주세요 [1]
1089한상욱9/13/201220310azure에 관한 질문입니다. [1]
1088김영대9/12/201222918DirectX.AudioVideoPlayBack 참조하여 wav 재생기를 제작하여 SmartClient 를 이용하여 aspx 페이지에 Embed 하는 과정의 질문 사항입니다. [2]
1087한우주9/10/201223634SSL 모든 웹페이지에 적용해야하나요? [2]
1086한우주9/4/201221272SSL 인증서 범용으로 사용하기 [3]
1085한우주9/4/201219155개발환경구성 18.3.1 에 대한 문의 [2]파일 다운로드1
1084김종하9/3/201220145team foundation express 2012에서 새 프로젝트 생성... [3]
1082김대경8/23/201219000windows2008 에서 ActiveX 사용 시 문제점. [3]
1091김대경9/20/201219104    답변글 [답변]: windows2008 에서 ActiveX 사용 시 문제점. [2]파일 다운로드1
1081Seon...8/20/201221044WCF 파일 업,다운로드 문제 [2]
1080배동선8/13/201220238정품 라이센스 인증 개발에 대해 조언을 구하고 싶습니다 [4]
1079송준호8/11/201218029basicHttpBinding stream 전송에 관하여 질문드립니다. [1]
1078Ho S...8/10/201217065윈도우폰 지도 구현에서 ㅠㅠㅠ 질문드립니다. [1]파일 다운로드1
1077한우주8/6/201219740웹서비스 호출 후 세션 유지하기 [1]
1076이성환8/2/201220439dynamic 변수 할당은 도대체 어디에???? [1]
1073pass...7/24/201219759c# 으로 만드는 음성인식/TTS 프로그램에 관련해서.. [3]
1072일반인7/23/201222474rss 만드는 방법 알려주실 수 있으신가요? [5]
1069임경훈7/20/201223824아래와 같은 오류후 IIS가 다운되는 현상이 발생합니다. [1]
1068신호철6/15/201221993ClassLibrary COM+ 등록 안되는 현상 [2]
1067김은주6/14/201232187소스세이프 사용시 pfx 파일 빌드 실패 [3]
1066너무초보6/3/201218588안녕하세요! 디렉토리 삭제 오류 질문 좀 드립니다. [4]
1065이성환5/23/201220569Assembly.LoadFrom Assembly.Load 의 차이점이 궁금합니다. [2]파일 다운로드1
1064푸우5/21/201219401GPU 디바이스 재시작시 WPF + .NET 3.5 기반 어플리케이션 UI 문제 [2]
1063발코더5/20/201219267귀신 곡할 상황 질문입니다. [3]
1062김규덕5/12/201219561ffmpeg 관련 조언 구합니다. [2]
... 61  [62]  63  64  65  66  67  68  69  70  71  72  73  74  75  ...