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)
888김재영7/5/201014358TFS에 반드시! SQL Report랑 SharePoint(or WSS)가 붙어야 합니까? [2]
887임동찬7/2/201015635WCF sendTimeout에 관하여... [1]
886김재영6/16/201015677스레드 선언시 (Parameterized/)ThreadStart에 정의되는 메소드의 위치에 질문이 있습니다. [3]
885장근배6/13/201023097Win32Exception 창 핸들 에러 [1]
883채동민6/10/201015276비동기 DB 쿼리관련 질문
884정성태6/10/201016727    답변글 [답변]: 비동기 DB 쿼리관련 질문
881최준영5/24/201016470load되지않은 아이템 load하는 방법? [1]
880임상일5/10/201018591VS2010 TestManager를 통한 UI Test 관련 질문입니다. [2]파일 다운로드1
879정용훈5/3/201019834wcf 인증 문제 [2]
878채동민4/20/201019008WCF에서 maxItemsInObjectGraph 오류 관련 질문드립니다. [2]
872날쌘돌이4/8/201021739Windows7 에서 IIS에서 폼인증 으로 디버깅.. [1]파일 다운로드1
871영초4/7/201017103실버라이트로 스캐너 구동 프로그램이 가능할까요? [1]
869김재영4/6/201015984이미 실행된 어셈블리 컨트롤 권한을 다른 어셈블리에서 가져올 수 있습니까? [2]
868Lime3/5/201019590WCF 에서의 DataTable 사용 [2]
867Dani...2/18/201019697Question - HTTP 401.3 on DELETE, PUT verbs [6]파일 다운로드1
865박근대2/16/201016197WCF 오류 문의. [1]
863날쌘돌이1/31/201018497ActiveX Cab에서 닷넷 dll 등록 [1]
862장근배1/28/201016252AppPolId를 알 수 있는 방법이 있는지요? [1]
864장근배2/1/201015906    답변글 [답변]: AppPolId를 알 수 있는 방법이 있는지요?
858생초보1/26/201016331안녕하세요.. 파일 생성 처리 문제로 .... [2]
857꼭지1/22/201022053How to support Basic + Windows authentication mode in WCF(RESTful service) [4]파일 다운로드2
856질의자1/13/201020024vcredist_x86 배포 관련 여쭙습니다. [1]
855임동찬1/13/201018123이벤트 핸들러와 쓰레드의 관계 2 [4]파일 다운로드2
854임동찬1/12/201018399이벤트 핸들러와 쓰레드의 관계 [1]
853장근배1/12/201018023압축 프로그램,, [1]
852임동찬1/6/201015417base.OnStart(agrs) [1]
... 61  62  63  64  65  66  67  [68]  69  70  71  72  73  74  75  ...