2012-08-08 53 views
0

我正在使用WPF應用程序進行串行通信,其中通過在主窗口(GUI)中從用戶獲取規範來創建串行端口,並將該端口作爲參數發送給後臺工作人員。我的問題是我的主窗口線程中有一個端口的數據收集事件,我使用它從串口讀取樣本數據並在BG線程中進行連續讀取。當使用我發送給BG工作人員的參數的端口時,我應該定義一個新的datareceived事件,還是將同一個事件工作?從標題data_received事件在哪個線程上運行?

private void SerialThread_DoWork(object Sender, DoWorkEventArgs e) 
    { 

     BGargs args = e.Argument as BGargs; 
     SerialPort BGport = args.PORT; 
     string MODE = args.MODE; 
     string filePath = args.filepath; 
     BGport.DataReceived +=new SerialDataReceivedEventHandler(BGport_DataReceived); 
     Dispatcher.BeginInvoke((Action)delegate() { run_button.IsEnabled = false; }); 
     switch (MODE) 
     { 
      case "EXT_trigger": 
       while (SerialThread.CancellationPending) 
       { 
        FileStream file = new FileStream(filePath, FileMode.Append, FileAccess.Write); 
        using (StreamWriter Writer = new StreamWriter(file)) 
        { 
         //code to continuously trigger and read data and then write to file 
        } 
       } 

        break; 
     } 
    } 

回答

0

問:

http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.datareceived.aspx

The DataReceived event is raised on a secondary thread when data is received 
from the SerialPort object. Because this event is raised on a secondary thread, 
and not the main thread, attempting to modify some elements in the main thread, 
such as UI elements, could raise a threading exception 

第二個問題:
不,你不要有其他附加的事件處理程序。這是所有同樣的單一串口對象,無論在這裏還是那裏。一旦你連接了一個事件處理程序,處理程序就會保留,不管你使用什麼對象。您可以通過args傳遞它,存儲在屬性中等。一旦+ ='被編輯到一個SerialPort對象,處理程序將一直保留,直到通過 - =形式明確地解除綁定它。

+0

@quetz ...感謝您的回覆,是的,我能夠使用相同的事件處理程序來執行我的操作。 – ranjith1512 2012-08-09 13:17:46