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

1  2  3  4  5  [6]  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
5842kr13/6/202312220publish 할 때 분석기 관련 dll 제외 [5]
5841guest3/3/202312544프로그램 판매 시 - Upgrade 버전 판매 [2]
5840joe3/2/202313431C# 클래스 라이브러리 수정 -> C++에서 참조시 함수 목록 갱신되지 않음. [4]파일 다운로드1
5839guest3/2/202313540윈도우 서비스 프로그램 - FORM 애플리케이션 감시서비스 [8]
5838랄랄라3/1/202311481event 사용 시 두 표현의 차이점이 있을까요? [1]
5837감사합니...2/28/202312364오라클 DB서버 접속관련 문의 드립니다.(Load Balancing, HA Events) [2]
5836박지범2/27/202311735static instance의 initialize 순서가 보장되나요? [6]
5835주민호2/25/202319787Windows Software Development Kit - 최신버전 1개 남기고 다 삭제하면 안되는지요? [10]파일 다운로드1
5834guest2/24/202311661Python IDE - 비주얼스튜디오 [3]
5833무지남2/23/202310891Async 메서드 그리고 나서 Bool 메서드 [5]
5832김지우2/21/202311645event와 delegate의 차이 , event를 써야하는 이유 [1]
5831이우람2/20/202313131ref 전역변수가 pinned가 될수 있나요? [2]
5830냉수마찰2/19/202312129C# GridView에 Column별 데이터 추가하는 방법에 대해 [1]
5829수박942/19/202314043키움 API를 윈폼과 WPF의 네임스페이스 없이 콘솔이나 WinUI3에서 사용할 수 있는 방법이 있나요? [2]파일 다운로드1
5828김재영2/19/202312379장기적으로는 this 구문을 안쓰는게 맞을까요? [2]
5827lee2/18/202314452파이썬 설치 오류 질문입니다 [1]
5826Syong2/14/202314248Socket 관련 Leak (OverlappedAsyncResult, OverlappedData) 관련 문의 [7]파일 다운로드1
5825박성원2/14/202313265Listview 컨트롤의 화면 전환 시 갱신 속도 [1]
5823검은콩2/13/202316730catch(Exception ex)의 line번호를 쉽게 알 수 없는지요? [7]
5822김지우2/11/202315704책을 보면서 sync, async 이해가 되지 않는 부분이 있습니다. [5]파일 다운로드2
5821검은콩2/9/202312330Async 신뢰성과 소켓데이터 [4]
5820차가워2/8/202312185다른 프로세스 실행 후 포커스 가져오기 [3]
5819취준생2/7/202312806WPF 관련 실무가 궁금합니다. [3]
5818윤길2/7/202312032ObservableCollection 에서 INotifyPropertyChanged 구현해야하나요? [2]
5817흰털너부리2/7/202311430배포 시 winform 실행 콘솔로그 보는 방법 [1]
5816흰털너부리2/6/202311843.net core json array validation 질문 드립니다. [1]
1  2  3  4  5  [6]  7  8  9  10  11  12  13  14  15  ...