Delegate : Help me!

In my codes, i want to using delegate to send puclic hexString from comport to some function. How can I write it This is some information about my code:


string
StringCom;
...........


//Every time my comport have data, this function will let data Triggered when a character is received and placed in the buffer.

private void OnDataReceived(object sender, System.EventArgs e)
{
string strReadBuffer;
strReadBuffer = myPortController.Read();// Reads everything in the receive queue
StringCom += strReadBuffer;
strReadBuffer ="";
}

// I want to write some function that convert StringCom to hexString and publishing this hexString.
// This is convert String that convert
StringCom to hexString

public void ConvertString()
{
if(StringCom.Substring(0,4)=="55AA")
{
hexString = StringCom.Substring(0,24);
if(StringCom.Length >24)StringCom = StringCom.Remove(0,24);
}
}


How can i using delegate and event, or publishing and subscribing with hexString

Thank you!



Answer this question

Delegate : Help me!

  • Diamond.Yu

    public delegate void DataReceivedHandler(object sender, DataReceivedEventArgs e);
    public event DataReceivedHandler OnDataReceivedEvent;

    private void OnDataReceived(object sender, System.EventArgs e)
    {
    string strReadBuffer;
    strReadBuffer = myPortController.Read();// Reads everything in the receive queue
    StringCom = strReadBuffer;
    ConvertString(StringCom);
    strReadBuffer ="";
    }
    public void ConvertString()
    {
    if(StringCom.Substring(0,4)=="55AA")
    {
    hexString = StringCom.Substring(0,24);
    if(StringCom.Length >24)StringCom = StringCom.Remove(0,24);
    }
    OnDataReceivedEvent(this, new DataReceivedEventArgs(hexString));
    }

    Also when instancing main object that have all this code you should subscribe to created event.

    this.OnDataReceivedEvent += new DataReceivedHandler(NewHexStringHandler);

    where NewHexStringHandler will be some method where you will do some work with that data.

    I use DataReceivedEventArgs class for event arguments just for good code practice.

    All this code was to show how to create delegates and events. But in your case you already have the event so there is no need for another one like this. But if you have some big work when converting some data or making some timeconsuming calculations with it, then maybe will need onother event, maybe also use multithreading because you can loose data if you work in single thread. But that is different story and multithreading has some additional work when you receive events from onother thread.



  • leo2

    Hi all,

    I try myself in someway about serial componet, that is
    franson.com/serialtools. In this code, i using port on read
    // In my Form, when it load i setup com port
    private void Form1_Load(object sender, System.EventArgs e)
    {
    SerialNET.License license = new SerialNET.License();
    license.LicenseKey = "my key go here...";
    port = new SerialNET.Port();
    port.BaudRate = 9600;
    port.ComPort = 3;
    port.Parity = 0;
    port.Enabled = true;
    port.StartTrigger = "Uay"; // Special information that i get in my port
    port.BufferSize = 12;
    port.OnRead += new SerialNET.OnRead(port_OnRead);
    ........
    }
    // And, when ever Port 3 have data (Com port send to my computer 500 bytes per seconds):

    private void port_OnRead(string Data)
    {
    port.StartTrigger = "Uay";
    byte[] myBytes = SerialNET.Port.StringToByteArray(Data);
    hexString = BitConverter.ToString(myBytes);
    hexString = hexString.Replace("-", "");
    Thread HexStringData = new Thread(new ThreadStart(XuLySoLieu));
    HexStringData.Start();
    }
    // Function
    XuLySoLieu is use to process data...
    public void XuLySoLieu()
    {
    Data = Convert.ToInt64(hexString.Substring(6,2), 16);
    Data1 =
    Convert.ToInt64(hexString.Substring(8,2), 16);
    ........
    if(
    Data == 7)
    {
    Thread Ghi_SoLieu = new Thread(new ThreadStart(TEMP2));
    Ghi_SoLieu.Start();
    }
    else if(
    Data == 3)
    {
    Thread Ghi_SoLieu = new Thread(new ThreadStart(HR));
    Ghi_SoLieu.Start();
    }
    }

    That is my way to get data and process it. And Data display is true as my way.

    But.... It some time change form it true Value to default value "---":
    public void Temp2()
    {
    float Temp2 = Data2 +200;
    if(Temp2>250)
    {
    Temp2 = Temp2 / 10;
    txtTemp2.Text = Temp2.ToString();
    }
    else txtTemp2.Text = "---";
    }

    For example, data change to "---". I had check data with others tools and can say for sure that it correct.
    If i remove this:
    txtTemp2.Text = "---";
    Data will display true and ofcource, can not change to default "---". But it can not clear data when
    Temp2<250 or Temp2 =0...

    Is there any way to fix this bug

    My code is not wrong, and can run true. But there is problem in display data. I try to using delegate, multi threading, and timer (I set timer_stick is 20ms) but this problem is still not fix.

    I don't understand why...






  • Menghraj

    Hi Boban Stojanovski,


    Thank you for your code and your advise. I had try to using your code but it is still wrong,

    first, in :
    ConvertString(StringCom);
    I try to fix this using threading:
    Thread start = new Thread(new ThreadStart(ConvertString));
    start.Start();

    and second in :
    DataReceivedEventArgs

    I try to add
    DataReceivedEventArgs class like this:
    public class DataReceivedEventArgs : EventArgs
    {
    public DataReceivedEventArgs (string hexString)
    {
    this.hexString = hexString;
    }
    public readonly string hexString;
    }

    When all of them are fix, i run test program and have error:

    An unhandled exception of type 'System.NullReferenceException' occurred in SimpleTerm.exe

    Additional information: Object reference not set to an instance of an object.

    it point to : OnDataReceivedEvent(this, new DataReceivedEventArgs(hexString));

    And, so error is still error.

    --------------------------

    I also think you are true when said that in my case, i need
    multithreading instead of publishing and subscribing. My comport send data 50 timer per seconds and it is hard to process all data in one threading. I had lost data when i receiver it. How about multithreading in my case

    Thank you!


  • Duece

    I think you are close to solution. I guess that the only left problem is that you throw event but it is unhandled. What this mean Always when you raise an event check if it's handled, and only then trow the event.

    if (OnDataReceivedEvent != null)
    OnDataReceivedEvent(this, new DataReceivedEventArgs(hexString));

    You change someting and now you use threads. If you work in 2005 probably will got a error when got an event from diferent thread and when you try to change something in main thread. This can be solved with Invoke method:

    private delegate void OnDataReceivedEvent(object sender, DataReceivedEventArgs e);
    private void OnDataReceivedHandler(object sender, DataReceivedEventArgse)
    {
    if (this.InvokeRequired)
    {
    this.Invoke(new OnDataReceivedEvent(OnDataReceivedHandler), new object[2] { sender, e });
    return;
    }
    //Do some work in main thread
    }



  • RGD_DBA

    Hi Beman,
    I haven't tried this code myself, so I'm just makin a guess here...are there any subscribers to the OnDataReceivedEvent event
    You should only fire the event if there are any subscribers, like this;

    if(OnDatareceivedEvent != null)
    {
    OnDataReceivedEvent(....);
    }

  • Delegate : Help me!