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)
5292아부리2/19/202014239XingApiNet 관련 질문 [3]
5291지현명2/15/202015551JsonConvert.Serialize 하고 Deserialize 할때 간헐적으로 한글 깨짐 현상 문의 합니다. [3]
5290베도빈2/15/202014582직접 제작한 사용자 정의 콘트롤 DLL, 실행파일에 포함시켜 배포할 수 있을까요? [1]
5288김성배2/14/202014793c# 참조추가 기능에서 DirectX 참조가 보이지 않아요.. DircetX 11 은 설치 되어 있습니다. [1]
5287C# 초...2/14/202013746프로그램 실행 질문 드립니다. [4]파일 다운로드1
5286gongs2/3/202022984윈도우 배율 및 레이아웃에 대한 질문입니다. [3]
5285강성욱1/27/202015465작업관리자에 표시되는 스레드 개수와 프로그램 내 스레드 개수 일치 [1]
5284이상준1/15/202022217출력창에 '스레드가 종료되었습니다' 문구 문의 [2]파일 다운로드1
5282봉봉이 1/13/202017638소켓 비동기 ReceiveTimeOut 구현 [9]파일 다운로드1
5281봉봉이 1/13/202015520소켓 비동기 ReceiveTimeOut 구현 [2]
5280sdd1/8/202014042데이터 저장, 배치파일 관련하여 질문드립니다. [4]
5279김창한12/27/201914625dsoframer ocx [3]
5278guest12/27/201913676CLR 스레드 풀 관련 질문 [1]
5277방문자12/26/201913461WindowsForm 질문드립니다. [3]
5276진우12/17/201916250c++/c# 에도 파이썬 가상환경 같은 기능 혹시 있는지 궁금합니다. [3]
5275송재필12/17/201915207아래 'c#8.0 프로그래밍 교제 예제 관련 문의 드립니다' 의 원인이 압축 파일의 문제인듯 합니다. [2]파일 다운로드1
5272정영훈12/13/201915785byte => string => byte 변환 문의드립니다. [5]파일 다운로드1
5270김세미12/3/201914259c#8.0 프로그래밍 교제 예제 관련 문의 드립니다. [4]
5269달려라라...12/2/201915426C# winform(framework) tabcontrol 에서 button 함수 관련 질문 [3]파일 다운로드1
5266엔벌잉11/26/201913847라즈베리파이 autostart관련 질문 [2]
5265해나11/25/201913605C# 6.0 책 내용 문의 [1]
5264김혜원11/18/201916803C# CodeSign에 대해 여쭤볼 것이 있습니다 [4]
5263정환맨11/17/201915299Task관련 질문입니다 [3]
5262닷린이11/14/201917092Dispatcher 와 synchronizationcontext의 관계가 궁금합니다. [6]
5260방문자11/13/201915062안녕하세요 도움받고 싶습니다 [1]
5259ming11/13/201914275string타입 파라메터로 넘길때 메모리 내부가 궁금합니다. [3]
... 16  17  18  19  20  21  22  23  24  25  [26]  27  28  29  30  ...