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

... 61  62  63  64  [65]  66  67  68  69  70  71  72  73  74  75  ...
NoWriterDateCnt.TitleFile(s)
987에스패스트8/3/201119646비밀글쓰기가 있으면 참좋을탠대 아쉽네요 ^^ 저 한가지만더.. [5]
986에스패스트8/3/201122918안녕하세요 ^^ 이렇곧도 있군요 ~ 참좋네요 질문 한가지 여쭤볼게요 [6]
985이성환7/27/201119223P/Inovke 관련 질문입니다. [4]파일 다운로드1
983이성환7/13/201128500Mouse이벤트 관련해서 질문있습니다. [10]파일 다운로드2
982궁굼이7/12/201119509TFS2010 사용관련 [2]
981김창욱7/11/201122436주식형태의 프로그램 처럼 SQL서버의 특정 필드 데이터의 변화가 있을때 재 클라이언트가 정보를 갱신 할 수 있게 하는 방법은 없을까요? [2]
980YJ7/7/201122028App Pool idle time 과 WCF 서비스의 비동기 function 호출. [3]
979왕초보7/1/201120402Apache + IIS Redirect [2]
9776/16/201123966웹컨트롤 어느거 쓰는게 좋나요 [1]
976박성준6/13/201119386VS2008 Add-in 구현 관련 질문 [4]
972김길6/6/201121727메모리 해제 예외 처리 관련.. [2]
971강동원5/29/201119206firebird install건 [1]
970임동찬5/18/201120053ASP.net 솔루션 디버깅 관련 [1]
969이성환5/4/201121627WMI 를 사용하지 않고 하드웨어 정보를 가져올 수 없을까요? [3]
968김동미4/28/201121026안녕하세요 다시 한번 문의를 드립니다.. [2]파일 다운로드1
967임동찬4/22/201123856C# using문 관련 [9]
964김동미4/18/201121457wcf IsOneWay 속성관련 문의 입니다..
965정성태4/18/201122919    답변글 [답변]: wcf IsOneWay 속성관련 문의 입니다..
966김동미4/19/201120258        답변글 [답변]: [답변]: wcf IsOneWay 속성관련 문의 입니다.. [1]
963최재훈4/12/201119051wcf inactivityTimeout 설정시 문의 사항이 있습니다. [2]
962임동찬4/8/201118718TFS 사용관련 [1]
961임동찬4/7/201118866XSD & XML & XmlCodeGenerator [2]
960임동찬4/5/201120783XML Schema Editor [4]
959immm3/24/201118413로그인 연동 어려운 건가요? [1]
958꼭지3/3/201120742Supporting compressed request in WCF 3.5 [5]
957임동찬2/21/201121013WCF channel faulted 관련 [2]
... 61  62  63  64  [65]  66  67  68  69  70  71  72  73  74  75  ...