将数据从类发送回调用者

时间:2011-04-04 20:11:20

标签: c# .net service

我正在寻找一种方法将类中的数据传递回父级,但是,它并不像听起来那么简单(例如访问类变量)。

我在我的申请中有这个电话:

protected override void OnStart(string[] args)
{
    eventLog1.WriteEntry("Start");

    // set up touchpad monitor
    cm = new COMManager("COM3",eventLog1);

}

COMManager看起来如下:

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());
    }

}

在serialPort_DataReceived中,事件记录器工作正常,但是,我希望能够在收到任何数据时将其传回主线程,因为我需要进行一些GUI修改。

任何关于从哪里开始的想法都会很棒。

1 个答案:

答案 0 :(得分:2)

一种方法是在COMManager课程中创建一个活动。只要收到数据,serialPort_DataReceived方法就会引发该事件。 COMManager实例的所有者可以订阅该事件。

您可能想要定义DataReceivedEventArgs

public class DataReceivedEventArgs: EventArgs
{
    // whatever you need here
}

你需要一个代表:

public delegate void DataReceivedEventHandler(object sender, DataReceivedEventArgs e);

然后你创建了这个事件:

// Inside COMManager
public event DataReceivedEventHandler DataReceived;

void serialPort_DataReceived(...)
{
    // do whatever
    if (DataReceived != null)
    {
        DataReceived(this, eventArgs);
    }
}

调用者以与订阅其他事件相同的方式订阅事件:

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;
}