Reputation: 1503
I have a WPF application which has a module for weighing loads. Since the serial port communication varies from one weighbridge to the other, I want to make the weighing module a separate dll.
I am creating a class library where I use the serial port for weighing loads. I need to return back the weight to the main program.
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;
}
But the data receieved is in a different thread. How will I get the weight back in my main program?
void spWeigh_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
// code here
}
Upvotes: 0
Views: 1907
Reputation: 1887
Could you not add an event to the library that your main program subscribes to and which is raised by your library, passing back the required data?
In your library:
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;
}
}
In your main program:
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
}
}
Upvotes: 1
Reputation: 2049
If the data does not need to be fast (i.e. less than once a second) you could write to a text file in one thread and read from it in the main thread
Upvotes: 0