Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8049861
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 5, 20262026-06-05T06:54:11+00:00 2026-06-05T06:54:11+00:00

I’m writing a C# console application that connects to a server via TCP and

  • 0

I’m writing a C# console application that connects to a server via TCP and receives periodic data back. I’m using some code I found here, which is a nice easy to use async client. Using this, my code starts up, makes a connection and then waits for events:

static void Main(string[] args)
        {
            agents = new ObservableCollection<AgentState>();
            EventDrivenTCPClient client = new EventDrivenTCPClient(IPAddress.Parse("192.168.0.1"), 5000);
            client.DataReceived += new EventDrivenTCPClient.delDataReceived(client_DataReceived);

               client.Connect();

                do
                {
                    while (!Console.KeyAvailable)
                    {
                        Thread.Sleep(50);
                    }

                } while (Console.ReadKey(true).Key != ConsoleKey.Q);

client.Disconnect();

       }

This starts up the app, connects to 192.168.0.1 on port 5000 and then starts listening for responses. When they’re received, I update an ObservableCollection called “clients” (comprised of object “ClientState”) with the results:

 static void client_DataReceived(EventDrivenTCPClient sender, object data)
    {
               string received = data as string;

        string parameters=received.Split(',');

        ClientState thisclient = clients.FirstOrDefault(a => a.clientName == parameters[0]);

        var index = clients.IndexOf(thisclient);
        if (index < 0)
        {

            ClientState newclient = new ClientState();
            newclient.clientName = clientname;
            newclient.currentState = state;
            newclient.currentCampaign = campaign;
            clients.Add(newclient);
        }
        else
        {
            clients[index].currentState = state;
            clients[index].currentCampaign = campaign;
        }

    }

To my great surprise, this all works fine: the code ticks along nicely, collecting the stats and adding to and updating the ObservableCollection. However, the problem is when I try to hook into the PropertyChanged… firstly, I add

   clients.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(agents_CollectionChanged);

to Main(), then I add:

    static void clients_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    {

                 foreach (INotifyPropertyChanged item in e.NewItems)
                     item.PropertyChanged += new PropertyChangedEventHandler(newagent_PropertyChanged); 
    }

I’d like this to call the newagent_PropertyChanged method (which just spits out to the Console at the moment) when anything changes in the ObservableCollection .. but some reason, as soon as a PropertyChanged event is fired, I get an exception in the “cbDataRecievedCallbackComplete” method in the TCP code:

Unable to cast object of type ‘ClientState’ to type ‘System.ComponentModel.INotifyPropertyChanged’.

… so somehow, the act of trying to raise a PropertyChanged is causing the “cbDataRecievedCallbackComplete” code to fire; it’s almost as if the events are “crossing paths”. If I “catch” the error the code grinds to a halt and doesn’t process any more incoming data.

I don’t have enough experience to know if this is a problem that I’ve introduced, or with the source code. I’ll put money on it being the former: can anyone see where there problem lies?

UPDATE: In response to the answers below, I’ve changed my class definition to look like:

  public class ClientState : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            var handler = PropertyChanged;
            if (handler != null)
                handler(this, new PropertyChangedEventArgs(propertyName));
        }

        public string agentName { get; set; }
        public string currentCampaign { get; set; }

        public string _currentState;
        public string currentState
        {
            get { return _currentState; }
            set
            {
                if (value != _currentState)
                {
                    _currentState = value;
                    OnPropertyChanged("CurrentState");

                }
            }
        }
    }

… so I’d expect any changes to “currentState” to trigger an event. However, I get an error in the same place, except now the error is:

Object reference not set to an instance of an object.

in the r.DataReceived.EndInvoke(result) line of the cbDataRecievedCallbackComplete.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-05T06:54:12+00:00Added an answer on June 5, 2026 at 6:54 am

    If your class definition for ClientState doesn’t look something like this

    public class ClientState : INotifyPropertyChanged
    

    then you cannot cast it to the type INotifyPropertyChanged. You aren’t getting a compile time exception because the e.NewItems collection is of type object so it will let you try to cast it to anything.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

That's pretty much it. I'm using Nokogiri to scrape a web page what has
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I have some data like this: 1 2 3 4 5 9 2 6
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have just tried to save a simple *.rtf file with some websites and
For some reason, after submitting a string like this Jack’s Spindle from a text
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I've got a string that has curly quotes in it. I'd like to replace
I am reading a book about Javascript and jQuery and using one of the
I have a French site that I want to parse, but am running into

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.