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

... 16  17  18  19  20  21  22  23  24  25  26  27  [28]  29  30  ...
NoWriterDateCnt.TitleFile(s)
5223김태균9/19/201914545책 소개 링크가 7.1버전판으로 이어집니다. [1]
5222냥냥이9/14/201914865프로그래밍 논리력이 많이 부족합니다 [3]
5219티지레몬9/9/201916892c# PCB 자동화 프로그램(윈도우 폼 위주로 작업) 제작 준비 [3]
5218민성9/9/201914986안녕하세요 WPF에서 xaml 안에 다른 xaml을 넣고 싶습니다. [1]파일 다운로드1
5216WPF9/8/201916031WPF에서 XAML Islands를 사용하여 Win2D를 사용하니 그래픽 품질이 저하됩니다. [2]파일 다운로드1
5215허송세월9/5/201915767중복실행 방지 관련 문의 [2]파일 다운로드1
5214Jang...9/4/201915247[DB 테이블의 데이터 변경에 대한 알림 처리] SQL-Server말고 MySQL은 불가능하겠죠? [1]
5213진우8/31/201914159c# 람다 변수 캡쳐 문의 [2]
5212심성보8/29/201916376Clipboard내 여러개의 이미지를 PictureBox로 불러오는 문제 [2]
5211최휘철8/24/201915359CLR20r3 관련된 윈도우 오류입니다. ㅠㅠ 도와주세요. / 아래글 관련하여 관련 파일 올려 드려요^^ [1]파일 다운로드1
5210최휘철8/23/201920241CLR20r3 관련된 윈도우 오류입니다. ㅠㅠ 도와주세요. [5]
5209세퉁8/21/201915142폰트 파일 속성 값을 가져오는 방법 질문 드립니다. [2]파일 다운로드1
5208홍길동8/19/201916173DebugDiag에서 .Net의 Stack Trace를 Windbg에서는 어떻게 볼 수 있나요? [3]
5207민성8/16/201914109네 소스 전체를 올리도록 하겠습니다. [2]파일 다운로드1
5206민성8/14/201914655전 재현 가능하다고 봤는데 다시올리도록 하겠습니다. [1]
5205miny...8/14/201914712안녕하세요 .WPF ListBox시 체크박스가 있는데 체크박스에서 체크가 되었는지 알수 있는 방법이 있을까요? [1]
5204영민8/8/201918290안녕하세요 디버깅시 콘솔창을 띠어서 볼수가 없나요? [7]
5202민성8/6/201914562WPF에서 <Application.Resources에 xaml에 있는 icon 값을 저장하고 xaml에 불러다 사용하고 싶은데요 [1]
5201김대훈8/3/201914660상속시 생성자에 대해 질문드립니다 [3]
5200농상7/30/201917454foreach로 데이터 변경 [2]
5190오리다람7/20/201914644질문드립니다. [3]
5189진우7/19/201914701C# 스레드풀 코어별 실행 문의 [2]
5188황태관7/19/201913889비주얼베이직 2019 실행 할때 마다.. [3]
5187플하7/19/201917048UWP 관련 궁금한 사항에 대해서 [1]
5186김대훈7/14/201915774박싱과 언박싱에 대해 [2]
5185농상7/13/201914068Nullable에 대해서 [1]
... 16  17  18  19  20  21  22  23  24  25  26  27  [28]  29  30  ...