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)
1347왕초보11/5/201419645    답변글 [답변]: C#에서의 함수포인터 [1]
1341영택10/29/201420872MFC Amazon S3 사용관련하여 질문드립니다. [2]
1344영택11/4/201417354    답변글 [답변]: MFC Amazon S3 사용관련하여 질문드립니다. [2]
1340감사합니다10/28/201422031c# wpf shdocvw internet explorer를 윈도우프레임으로 집어 넣을 수 있는지 궁금합니다. [3]파일 다운로드1
1338헬프미10/28/201422809tcp 소켓의 SYN_RECV 상태에 대하여 질문있습니다. [3]
1336이소정10/27/201417829filestream seek에 대해 질문있습니다. [1]
1337이소정10/28/201418655    답변글 [답변]: filestream seek에 대해 질문있습니다.파일 다운로드1
1339이소정10/28/201421775        답변글 [답변]: [답변]: filestream seek에 대해 질문있습니다. [2]파일 다운로드2
1335황지혜10/24/201422319psexec 관련 질문드립니다. [1]
1334dell10/24/201418382여기가 있는줄 모르고 방명록에 남겼네요 ㅠㅠ 방명록 한번만 봐주시면 안될지요? [1]
1333왕초보10/24/201418735Bitmap 질문 [5]
1332김동진10/16/201425402clickonce 와 smartscreen filter 기능에 대해서 [2]
1331궁굼합니다10/8/201418849loopback adapter 자동 설치가 가능 한가요? [2]
1330이현중10/8/201421511파일 다운로드 방법 문의 [2]파일 다운로드1
1329popo10/2/201418926싱글톤과 싱글톤 소멸자에 대해 궁금점이 있습니다. [1]
1328달쏭9/25/201419968WCF Service측에서 parameter 값이 null이 오는 이유를 알고 싶어요. [2]
1326궁굼합니다9/19/201418981VB의 Shell 기능과 완벽히 똑같은 기능의 함수 [4]
1325지현태9/18/201418677WPF 의존속성과 바인딩에 대한 질문입니다.. [1]파일 다운로드1
1324popo9/17/201417662wcf 질문 드립니다. [1]
1323Anon...9/17/201420352인스턴스와 객체의 차이 [1]
1322김영대9/16/201420236죄송하지만 .NET 관련 질문게시판이지만 혹시 ASP.NET MVC에 대해서 질문 드려도 됩니까 (__);; [2]
1321부탁드립...9/15/201422440윈도우 어플리케이션 개발 방법(?) 에대해(직접적인 코드라기보단 프로젝트 방향??) [14]
1320소켓서버...9/13/201422775서로다른 포트번호로 로컬 Socket 서버를 개설시 Close 문제 입니다. [2]
1319ㅇㅇ9/12/201422837134쪽 예제 오타 [3]
1318블루투쓰9/12/201418950page 184 질문드립니다. [1]
1316서동원8/21/201425075ActiveX 개체가 이 속성 또는 메서드를 지원하지 않습니다. [1]
... 46  47  48  49  50  51  52  53  [54]  55  56  57  58  59  60  ...