Click here to Skip to main content
15,868,016 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
First I am subscribing to an event and then in the method which will be executed when that event occurs i am unsubscribing it.But still I think it is getting fired many times.

What I have tried:

using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SerialPortHexCommunication
{
    public class Program
    {
        private static bool unsubscribe=false;

        static void Main(string[] args)
        {

            SerialPort port = new SerialPort();
            port.PortName = "COM5";
            port.Parity = Parity.None;
            port.BaudRate = 9600;
            port.DataBits = 8;
            port.StopBits = StopBits.One;
          
            if (port.IsOpen)

            {
                port.Close();
                port.Dispose();
            }
             port.Open();

            byte[] bytesToSend = new byte[6] { 0xD0, 0xF2, 0xFF, 0x00, 0x06, 0xC7 };

            port.Write(bytesToSend, 0, bytesToSend.Length);

      
            port.DataReceived += new SerialDataReceivedEventHandler(new cEventHandler().DataReceivedHandler);

            port.DataReceived -= new SerialDataReceivedEventHandler(new cEventHandler().DataReceivedHandler);

            Console.ReadKey();
            port.Close();
            port.Dispose();

            
           

        }

      
    }
}



using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SerialPortHexCommunication
{
   public class cEventHandler
    {
        public void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
        {//this In data receive message should be printed only once
         //as i am unsubscribing but it get printed many times.
            Console.WriteLine("In data receive");
            SerialPort port = (SerialPort)sender;
            port.DataReceived -= new SerialDataReceivedEventHandler(DataReceivedHandler);

            int bytes = port.BytesToRead;
            byte[] buffer = new byte[bytes];

            if (port.BytesToRead > 1)
            {
                port.Read(buffer, 0, bytes);
            }

            foreach (byte item in buffer)
            {
                Console.WriteLine(item);

            }

            port.DataReceived -= new SerialDataReceivedEventHandler(new cEventHandler().DataReceivedHandler);
            //Console.ReadKey();
        }
    }
}
Posted
Updated 6-Jun-18 4:05am

Please, look at your code!
Why would you write this:
            SerialPort port = new SerialPort();
...          
            if (port.IsOpen)

            {
                port.Close();
                port.Dispose();
            }
             port.Open();
If it's a new port, it can't be open - which is just as well, as your app would then crash immediately as you tried to oipen a port you had just Disposed...

The second thing to note is that multiple DataReceived events are exactly what you should expect: Serial data is called that because it arrives in a serial fashion, byte by byte instead of as a "managed packet" of information: each byte can cause a separate DataReceived event to fire.

I told you this two days ago!
 
Share this answer
 
DataReceived
event should be subscribed before calling
Open()
method of
SerialPort
class.

As per your result event is called many times- In my case event will be called only in case of any response comes from another paired port.

For ex. Paired ports are - "COM5" <-> "COM3" so when any response will come from "COM3" port then the
DataReceived
event will be called.

There is no need to unsubscribe the event.
 
Share this answer
 
Comments
Nishikant Tayade 6-Jun-18 1:56am    
@ChanderParkashMourya as you said "when any response will come from "COM3" port then the event will be called."

But what i want is that it should just stop asking when first response comes, in that case "In data receive" will be there only once,then again ask for data and so on.
is it possible?
That's why i was trying to unsubscribe.
Chander Parkash Mourya 6-Jun-18 3:18am    
DataReceived event will be called to separate thread and you can not unsubscribe the event outside of thread.
for more information you can follow this link -
https://msdn.microsoft.com/fi-fi/library/system.io.ports.serialport.datareceived(v=vs.110).aspx
Quote:
port.DataReceived += new SerialDataReceivedEventHandler(new cEventHandler().DataReceivedHandler);
port.DataReceived -= new SerialDataReceivedEventHandler(new cEventHandler().DataReceivedHandler);

You've added two handlers to the event. Therefore, every time the event is raised, your event handler will be called twice.

Quote:
port.DataReceived -= new SerialDataReceivedEventHandler(new cEventHandler().DataReceivedHandler);

That line will have no effect.

When a delegate pointing to an instance method is removed from an event, the object reference to which the delegate points is included as part of its identity. Since you're creating a new instance of your class, the delegate you create is not equal to any of the registered handlers for the event, so removing it doesn't do anything.

The previous port.DataReceived -= new SerialDataReceivedEventHandler(DataReceivedHandler); line should already remove the handler, so you can just delete this line.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900