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)
1528김개똥2/14/201516748좀 관련없는 질문이지만, 정말 답답하고 찾는데 명확한 해답 찾지못해 질문 올립니다. <Windows 사용자 인증> [1]
1527방문자1/27/201518131System Timer의 Tick에서 Backgroundworker를 호출하면 스레드 문제가 있을까요? [1]
1526황상대1/26/201520280C# 마샬링 관련 질문이 있습니다. [1]
1525Ji-y...1/19/201518874시작하세요 C# 프로그래밍 도서에 관한 질문입니다. [1]
1523임종복12/31/201426813windows 2008 r2에서 ms-sql 2008 서버사용시 tls문제점 [3]
1524임종복1/4/201521322    답변글 [답변]: windows 2008 r2에서 ms-sql 2008 서버사용시 tls문제점 [2]
1521윤대욱12/19/201418031C++ 에서 서버와 클라이언트를 나누어서 구조체 전달에 대해서 궁금합니다. [1]파일 다운로드1
152012/10/201418652datetime관련해서요 [1]
1516aTo12/1/201417727wpf 배포관련. [3]
1514얄미운제리11/17/201418595[C# Mono]Mono Chart 개발 문의드립니다. [1]
1355미나리나물11/13/201416026RDP 접속 방식 질문드리고 싶습니다. [1]
1353송용국11/10/201415222TeamFoundationServer 에 소스를 Target서버로 옮기는(내려주는) 방법 있나요? [1]
1351blue...11/7/201420577c# webbrowser 모바일환경 접속 [1]
1350에메11/7/201420414WCF namedpipe 퍼블리싱 충돌 문제 [3]파일 다운로드1
1349Chun...11/6/201424544Microsoft. Net Framework 액세스 거부 오류...... [2]
1348김준석11/6/201420716 Mini dump 기록 안되는 현상 [2]파일 다운로드1
1346개미11/5/201435191https페이지에서 http서버에 있는 이미지 파일 호출시 보안 오류 [8]
1345장구니11/4/201418946AWS 인스턴스를 만들었는데 [1]
1343h11/2/201418580안녕하세요 [1]
1342왕초보11/1/201423430C#에서의 함수포인터 [13]
1347왕초보11/5/201418150    답변글 [답변]: C#에서의 함수포인터 [1]
1341영택10/29/201419325MFC Amazon S3 사용관련하여 질문드립니다. [2]
1344영택11/4/201415907    답변글 [답변]: MFC Amazon S3 사용관련하여 질문드립니다. [2]
1340감사합니다10/28/201420499c# wpf shdocvw internet explorer를 윈도우프레임으로 집어 넣을 수 있는지 궁금합니다. [3]파일 다운로드1
1338헬프미10/28/201421217tcp 소켓의 SYN_RECV 상태에 대하여 질문있습니다. [3]
1336이소정10/27/201416585filestream seek에 대해 질문있습니다. [1]
... 46  47  48  49  50  51  52  [53]  54  55  56  57  58  59  60  ...