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)
5411원격11/20/202015515visualstdio로 웹 사이트로 만들었을때 원격 디버깅이 가능한가요? [1]
5410최성재11/16/202016094vcpkg로 GDCM 내려받을 때 USE_VTK 설정하는 방법-2번째 질문 [1]파일 다운로드1
5409민성11/16/202018987혹시 다른 질문이긴 한데요 [1]
5408최성재11/16/202015843vcpkg로 GDCM 내려받을 때 USE_VTK 설정하는 방법 [1]
5407민성11/11/202013968안녕하세요 yield return에 대해서 [1]
5406질문자11/10/202015133안녕하세요 wcf nettcpbinding의 timeout에 관해서 질문이 있습니다. [2]
5405민성11/9/202014959안녕하세요 이번에도 또 어려운 질문 같습니다. [1]
5404박진우11/6/202017758안녕하세요. SqlParameter 생성자 관련 질문 있습니다. [1]
5403민성11/5/202017438그리고 한가지만 죄송하지만 더 질문 드리겠습니다. [1]
5402민성11/5/202017266안녕하세요 책을 보고 질문하나만 드릴깨요 [2]
5401민성11/3/202016315안녕하세요 이번에도 질문 하나만 드리겠습니다. [2]
5400진우10/29/202016030SQL Server 관련 몇가지 문의 [2]
5399Wpf개...10/21/202016182Binding 된 항목의 갱신 시 간헐적 끊어짐 발생 문제. [2]
5397나그네10/15/202015309.net Core 3.1 에서 Entity Framework 와 ADO.NET 선택에 관해 여쭤봅니다. [2]
5396여정욱10/15/202015000CLR heap 관련 질문 2 [2]
5395여정욱10/14/202017644CLR heap 관련 질문 [2]
5394진우10/12/202021664닷넷코어 (닷넷5) winform wpf는 리눅스/맥에서도 가능한가요? [2]
5393김세용9/23/202017028C#에서 대량의 클래스를 빠르게 생성하는 방법이 없을까요? [6]
5392전경호9/22/202016567WPF에서 WindowsFormsHost의 메모리 누수 문제 때문에 문의드립니다. [1]파일 다운로드1
5391민성9/22/202015930안녕하세요 항상 감사드립니다. 하나 질문 드리겠습니다. [1]
5390alow...9/18/202019040System.AccessViolationException 보호된메모리 부분 예외처리 [1]
5389C# 8...9/18/202015928후위 증감 연산자 오버로딩 방법 좀 알려주세요 [4]
5388영귤9/17/202019818Nullable reference type 에 Non-nullable reference type 을 대입해도 경고가 발생하지 않습니다. [2]
5387하태9/17/202016732안녕하세요! 비동기 통신과 관련하여 질문하나만 드리겠습니다! [3]
5386박민웅9/16/202019792정성태 스승님 안녕하세요 !! [1]
5385영귤9/12/2020157543항 연산자에 ref 지원? [1]
... 16  17  18  19  20  21  [22]  23  24  25  26  27  28  29  30  ...