티스토리 뷰

728x90
반응형

serial.DataReceived  이벤트는 주 스레드가 아닌 보조 스레드에서 발생 UI요소인 Binding 된 TextBox의 Text를 변경하려 하면 Thread Exception 오류가 발생한다.


<UI Thread Exception>

 


UI

      <TextBox Margin="10,15,10,5" x:Name="txtUsername" Grid.Row="1"  Width="Auto" FontSize="19" 
                                Text="{Binding RF_IDS}" >

 

ViewModel

        private string? _rF_IDS;
        public string? RF_IDS
        {
            get { return _rF_IDS; }
            set
            {
                _rF_IDS = value;
             OnPropertyChanged(nameof(RF_IDS));
            }
        }

public HomeViewModel()
{
  RFConnectCommand = new RFConnectCommand(this);
}

Command

private readonly HomeViewModel _viewModel;
public RFConnectCommand(HomeViewModel viewModel)
        {
            _viewModel = viewModel;
            _viewModel.PropertyChanged += ViewModel_PropertyChanged;
        }


SerialPort serial = new SerialPort();

 public void Execute(object? parameter)
        {
            serial_DataReceive();
            InitSerialPort(); // Serial Port 
        }

private void serial_DataReceive()
        {
            serial.DataReceived += new SerialDataReceivedEventHandler(serial_DataReceived);
        }

private delegate void UpdateData(string data);
private void UpdateData_new(string data)
        {
            App.Current.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate
           {
               _viewModel.RF_IDS = data;
            }));
     }

 

        int byte_int = 0;
        byte[] rcvByteFinal = new byte[10];

private void serial_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
            
                if (!serial.IsOpen) return;

                int bytes = serial.BytesToRead;
                byte[] buffer = new byte[bytes];
                byte[] rcvByte = new byte[bytes];

                serial.Read(buffer, 0, bytes);

                Array.Copy(buffer, 0, rcvByte, 0, bytes); // 처음 바이트를 rcvByte에 넣는다.

                Array.Clear(buffer, 0, bytes); // buffer 초기화

                Array.Copy(rcvByte, 0, rcvByteFinal, byte_int, bytes); //카피해서 rcvByteFinal에 넣고 또 놓고.

                byte_int += bytes;  // 누적 Byte Length

                for (int i = 0; i < bytes; i++) //메인 루프
                {

                    if (rcvByte[i] == 0x03) //0x1A  ETX 
                    {
                        if (rcvByteFinal != null)
                        {

                             // 카드 번호를 모두 받아 왔으니 이제 카드번호를 처리한다.

                            string H2Asc = HexStringToASCII(rcvByteFinal);

                            UpdateData RF_EventHandler = new UpdateData(UpdateData_new);
                            RF_EventHandler.Invoke(Result_RFID); 

                            rcvByteFinal = null; //초기화
                            rcvByteFinal = new byte[10]; // 카드번호 10자리 세팅
                            byte_int = 0; // 누적 byte Length 초기화
                        }
                    }
                }
                Array.Clear(rcvByte, 0, bytes); // 
              
            }      

           catch (TimeoutException)
            {
            
            }

        }

 

  public string HexStringToASCII(byte[] hexstring)
        {
            byte[] bt = hexstring;// strToToHexByte(hexstring);
            string lin = "";
            for (int i = 0; i < bt.Length; i++)
            {
                lin = lin + bt[i] + " ";
            }

            string[] ss = lin.Trim().Split(new char[] { ' ' });
            char[] c = new char[ss.Length];
            int a;
            for (int i = 0; i < c.Length; i++)
            {
                a = Convert.ToInt32(ss[i]);
                c[i] = Convert.ToChar(a);
            }

            string b = new string(c);
            return b;
        }

참고: SerialPort.DataReceived 이벤트 (System.IO.Ports) | Microsoft Docs

반응형

'WPF' 카테고리의 다른 글

SqlDataReader to DataTable  (0) 2022.10.14
MSSQL HashBytes Sqlparameter Error  (0) 2022.06.30
Radio Button/ CheckBox Null Check  (0) 2022.06.20
C# DataTable AsEnumerable Sum, Count Linq쿼리  (0) 2022.02.14
C# LINQ Left join of DataTables  (0) 2022.02.09
댓글