iT邦幫忙

0

完全沒碰過程式,新手詢問c# seriaport 接收問題,。D220D309需不停讀取,使用迴方式一直再傳送指令。請問我接收部分是哪裡出問題?更改過變數但接收就會瘋狂跑到catch()例外狀況

private void Form1_Load(object sender, EventArgs e)
    {
        GetMobus.com();
        GetMobus.Point();
        //GetMobus.Weight();
        update();
    }    
 private Thread thread;
    public  void update()//我更新UI跑回圈地方
    {           
        try
        {
            thread = new Thread(() =>
            {
               while (true)
               {
                   GetMobus.Weight();
                   Debug.WriteLine(GetMobus.weight);
                   var m = new UpdateUICallBack_Text(Test);
                   Invoke(m, GetMobus.weight);
               }
           });

            thread.IsBackground = true;
            thread.Start();
        }
        catch 
        {
            Thread.ResetAbort();
        }        
    }
    private void Test(string strValue) 
    {
        mobusBindingSource.DataSource = GetMobus;
        mobusBindingSource.ResetBindings(false);
    }

以下是寫在Mobus.CS

serialPort = new SerialPort(Ports[0],38400,Parity.Even,7,StopBits.One);   
var D220_2 = ThreadProc(D220);//接收到卻是""
var D309_1 = ThreadProc(D309);//接收到卻是D220回傳的指令


public string ThreadProc(string Data)
    {
        var Data1 = "";
        serialPort.Write(Data);
        var aaaa = new Thread(() => {
        try
        {
            
            lock (serialPort)
            {
                Data1 = serialPort.ReadExisting();
                Thread.Sleep(30);//28OK   
                if (Data1.Length != 23)
                {
                    Data1 = Check(Data);
                    Debug.WriteLine("Data2:" + Data1);
                    for (int i = 0; i < 3; i++)
                    {
                        Data1 = serialPort.ReadExisting();
                        Thread.Sleep(20);
                        var aa = Check(Data1);//檢查碼
                        if (aa == Data1) { break; }
                    }
                }           
            }
        }
        catch
        {
            lock (serialPort)
            {
                Data1 = serialPort.ReadExisting();
            }
        }
        });
        aaaa.Start();
        return Data1;
    }
    
    
fillano iT邦超人 1 級 ‧ 2020-08-28 09:52:20 檢舉
catch裡面應該處理例外,而不是繼續讀取。
catch(Exception e) {
Console.WriteLine(e.Message);
}
至少可以讓你看到錯誤的訊息來找原因。

尚未有邦友回答

立即登入回答