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

... 31  32  [33]  34  35  36  37  38  39  40  41  42  43  44  45  ...
NoWriterDateCnt.TitleFile(s)
5078꾸엉10/29/201815396C# 7.1 185~187p 질문입니다. [2]
5077윤현수10/29/201822373setup파일 설치 이후 실행이 안되는 현상 [11]
5074진우10/28/201815298C# 생성과 동시에 초기화 하는 코드 문의 [2]
5073돌고래10/27/201815207c# 공부 방향 질문 드립니다. [3]
5072엔벌잉10/24/201814910C# textbox, button질문입니다! [4]파일 다운로드1
5071엔벌잉10/23/201816294C#윈도우폼 질문입니다!! [2]
5070진우10/17/201816349Visual Studio 서비스팩과 업데이트 차이 문의 [2]
5069감자10/12/201816975빌드 구성을 재설정하는 방법이 있을까요? [1]파일 다운로드1
5068누오10/10/201815653ASP Core 2.0 에서 dll안에 있는 뷰 읽어들이는 방법? [1]
5067김정민10/5/201815973다른 윈도우가 깨지는 현상을 막을 수 있을까요 [3]
5066로니브10/4/201816643ASP.NET MVC에서 View 파일 숨기는법? 보안처리 하는법? 관련 질문.. [1]
5065키모10/1/201818278문자 질문입니다. [3]
5064로니브10/1/201817622클래스 라이브러리에서 .cshtml파일을 추가하는 방법은 없나요? [3]
5063진우9/28/201816360ADO.net 과 Entity Framework 차이 문의 [2]
5062테스트9/27/201816852C# import file 의 구조체 배열 선언 및 호출에 대해 문의. [3]
5061안녕하세요9/13/201817244c# 프로그래밍 관련 문의 [1]
5060임민재9/8/201816293c# install 파일 생성 시 문제가 발생하였습니다 [1]파일 다운로드1
50599/7/201815739Winform TextBox 포커스 유지하는 방법 질문 [파일첨부] [1]파일 다운로드1
50589/5/201820102Winform TextBox 포커스 유지하는 방법 질문 [3]
5056박종윤8/30/201818788c# dll을 C++에서 사용 시 event 호출 [4]파일 다운로드1
5055초보자8/29/201817601asp.net 에서 다른 서버의 iis를 stop하는 batch file을 실행시키는데 동작하지 않습니다. [5]
5054사도신8/29/201816214[wpf] textbox insert overite 모드시에 [4]파일 다운로드1
5053엿장수8/26/201815142directshow filter 에서의 IMediaSample 의 시간에대한질문입니다 [1]
5052오명현8/26/201815426Tcp소켓 실습 Exeption 도와주세요! [4]파일 다운로드1
5049오명현8/23/201815163책 477페이지 내용 중 이해가 안가는 부분이 있어 질문드립니다. [1]
5048오명현8/23/201814658포트 관련 질문 하나더 있습니다. [1]
... 31  32  [33]  34  35  36  37  38  39  40  41  42  43  44  45  ...