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

... 46  47  48  49  50  51  52  53  54  [55]  56  57  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
1309서동원8/12/201418105안녕하세요. embeded dll과 관련하여 질문드립니다. [4]
1308김솔8/11/201422257리스트뷰에서 중복파일체크를 하고싶습니다. [3]
1306이상현8/7/201415827Entity 프레임웍에서 테이블만 추가로 등록하는 방법
1307이상현8/7/201416331    답변글 [답변]: 자답이네요. [1]
1305popo8/7/201417445wpf UserControl List 바인딩 질문 입니다. [1]
1304민경수8/7/201420475네이버 카페에 구글 스프레드 시트 삽입 [1]
1303김동진8/7/201417610vmware환경에서 Guest IP를 192대역으로 받을 수 있는 방법은 없을까요~? [3]
1302김문경7/31/201416520스마트클라이언트 오라클 연결 [1]
1314이재균8/20/201416609    답변글 [답변]: 스마트클라이언트 오라클 연결
1300아로스7/28/201430168c# 인터넷 임시 파일 삭제 문의 [12]파일 다운로드1
1299서동원7/28/201418553안녕하세요. 혹시 Internet_Zone과 관련된문제인가 해서 질문드립니다. [1]
1298(non...7/25/201424749(글쓴이의 요청으로 삭제합니다.) [15]
1295서동원7/22/201419722안녕하세요. 스마트클라이언트에 대해 질문드립니다. [2]파일 다운로드1
1294(non...7/20/201417992(글쓴이의 요청으로 삭제합니다.) [2]
1293VS20...7/20/201419404VS2013 Ultimate에 Windows Phone 프로젝트 템플릿 추가 방법 문의 [1]파일 다운로드2
1292(non...7/20/201416909(글쓴이의 요청으로 삭제합니다.) [2]
1291zino7/16/201418610chromium 배포본 만들기~ [1]
1290(non...7/13/201419388(글쓴이의 요청으로 삭제합니다.) [3]
1288박주만7/8/201428614C# 서비스 기반 데이터베이스(mdf) & InstallShield Limited Edition 설치 및 배포 [2]파일 다운로드1
1287김용환7/8/201426718오라클 db 사용관련 문의입니다. [4]파일 다운로드1
1286C#조으다7/8/201416905WebBrowser 공유기 관리 웹 페이지 인증 [3]
1285C#조으다7/5/201417253IE DocumentComplete 이벤트가 발생되지 않습니다. [2]
1284(non...7/4/201417561(글쓴이의 요청으로 삭제합니다.) [3]
1283김영대7/3/201420361안녕하십니까 정성태님 죄송하지만 SmartClient 에 관한 질문이 있습니다. [9]
1282(non...7/2/201417440(글쓴이의 요청으로 삭제합니다.) [2]
1281(non...7/1/201418707(글쓴이의 요청으로 삭제합니다.) [4]
... 46  47  48  49  50  51  52  53  54  [55]  56  57  58  59  60  ...