Send data back from class to caller
I'm looking for a way to pass data from a class back to the parent, however, it's not as simple as it sounds (e.g. accessing a class variable).
I have this call in my application:
protected override void OnStart(string[] args)
{
eventLog1.WriteEntry("Start");
// set up touchpad monitor
cm = new COMManager开发者_如何学C("COM3",eventLog1);
}
And the COMManager looks as follows:
class COMManager
{
static SerialPort _serialPort;
EventLog eventlogger;
public COMManager(string portname,EventLog eventlogger)
{
this.eventlogger = eventlogger;
this.eventlogger.WriteEntry("started com porter");
StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
//Thread readThread = new Thread(Read);
// Create a new SerialPort object with default settings.
_serialPort = new SerialPort();
// Allow the user to set the appropriate properties.
_serialPort.PortName = portname;
_serialPort.BaudRate = 9600;
_serialPort.Parity = (Parity)Enum.Parse(typeof(Parity), "0");
_serialPort.DataBits = 8;
_serialPort.StopBits = (StopBits)Enum.Parse(typeof(StopBits),"1");
// Set the read/write timeouts
_serialPort.ReadTimeout = 500;
_serialPort.WriteTimeout = 500;
_serialPort.Open();
_serialPort.DataReceived += serialPort_DataReceived;
}
void serialPort_DataReceived(object s, SerialDataReceivedEventArgs e)
{
this.eventlogger.WriteEntry(Convert.ToChar(_serialPort.ReadChar()).ToString());
}
}
In serialPort_DataReceived, the event logger works fine, however, I want to be able to pass this back to the main thread when any data is received as I need to do some GUI modifications.
Any ideas on where to start would be great.
One way would be to create an event in your COMManager
class. The serialPort_DataReceived
method would raise that event whenever data is received. The owner of the COMManager
instance can subscribe to the event.
You'll probably want to define a DataReceivedEventArgs
:
public class DataReceivedEventArgs: EventArgs
{
// whatever you need here
}
And you'll need a delegate:
public delegate void DataReceivedEventHandler(object sender, DataReceivedEventArgs e);
And then you create the event:
// Inside COMManager
public event DataReceivedEventHandler DataReceived;
void serialPort_DataReceived(...)
{
// do whatever
if (DataReceived != null)
{
DataReceived(this, eventArgs);
}
}
The caller subscribes to the event the same way that you subscribe to other events:
protected override void OnStart(string[] args)
{
eventLog1.WriteEntry("Start");
// set up touchpad monitor
cm = new COMManager("COM3",eventLog1);
// subscribe to the event.
cm.DataReceived += this.DataReceived;
}
精彩评论