0

我有一个 WPF 应用程序,它有一个用于称重负载的模块。由于串行端口通信因地磅而异,因此我想将称重模块设为单独的 dll。

我正在创建一个类库,我在其中使用串行端口来称重负载。我需要将重量返回给主程序。

double GetWeights()
{

 spWeigh = new SerialPort("COM1", 2400, Parity.None, 8, StopBits.One);
            spWeigh.RtsEnable = false;
            spWeigh.DtrEnable = false;
            spWeigh.Handshake = Handshake.None;
            spWeigh.ReadTimeout = 10000;
            spWeigh.DataReceived +=spWeigh_DataReceived;

}

但是收到的数据在不同的线程中。我将如何在我的主程序中恢复体重?

 void spWeigh_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
      // code here
    }
4

2 回答 2

1

您不能向您的主程序订阅的库添加一个事件,该事件由您的库引发,并传回所需的数据吗?

在您的图书馆中:

class YourLibrary
{
    public delegate void RawDataEventHandler(object sender, RawDataEventArgs e);
    public event RawDataEventHandler RawDataReceived;

    void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        string ReceivedData = _serialPort.ReadExisting();
        if (RawDataReceived != null)
            RawDataReceived(this, new RawDataEventArgs(ReceivedData));
    }
}

class RawDataEventArgs : EventArgs
{
    public string Data { private set; get; }

    public RawDataEventArgs(string data)
    {
        Data = data;
    }
}

在您的主程序中:

class MainProgram
{
    YourLibrary library = new YourLibrary();
    library.RawDataReceived += new YourLibrary.RawDataEventHandler(library_RawDataReceived);

    void library_RawDataReceived(object sender, RawDataEventArgs e)
    {
        // Your code here - the data passed back is in e.Data
    }
}
于 2012-07-10T15:16:52.093 回答
0

如果数据不需要很快(即每秒少于一次),您可以在一个线程中写入文本文件并在主线程中读取

于 2012-07-10T15:15:41.030 回答