Expose an event from your dll. Every time the data
SerialDataReceivedEventHandler
is called, invoke the event:
public class Scale : IDisposable
{
SerialPort port = new SerialPort("com", 9600, Parity.None, 8, StopBits.One);
public Scale()
{
port.DtrEnable = true;
port.DataReceived += OnWeightChanged;
}
public delegate void ScaleWeightChangeHandler(object sender, string weight);
public event ScaleWeightChangeHandler WeightChanged;
private void OnWeightChanged(object sender, SerialDataReceivedEventArgs serialDataReceivedEventArgs)
{
if (WeightChanged != null)
WeightChanged(sender, Weight());
}
public string Weight()
{
try
{
if (port.IsOpen == false)
{
port.Open();
}
port.DtrEnable = true;
return port.ReadLine();
}
catch (Exception ex)
{
return "";
}
}
#region Corrected from comments below
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
port.DataReceived -= new SerialDataReceivedEventHandler(getPesha);
}
if (port != null)
{
if (port.IsOpen)
{
port.Close();
}
port.Dispose();
}
}
#endregion
}
(Bet I'm not the first solution response, but it's gotta be the best ^_^ )
Hope that helps
Andy
EDIT: corrected the Dispose methods from comments below