Hi all, I've written a server programme that accepts UDP packets from a client programme that I have also written... It's been working fine but recently I've started to get an exception...

Here is the the code that's causing the problem:

public delegate void AddnewText(string str);
public void AddTextToTextBox(string str)
        {
            if (this.tbCurrent.InvokeRequired)
            {
                this.Invoke(new AddnewText(AddTextToTextBox), str);                
            }
            else
            {
                this.tbCurrent.Text += str;
            }
        }

When a packet comes in to the Server app, it's placed into a textbox called tbCurrent then the contents of that are sent to a textbox on the same form called displayTextBox (sorry about the awful naming conventions!)

The packet will be displayed in the displayTextBox meaning that the packet has successfully arrived, but for some reason I get an ObjectDisposedException informing me that I cannot write to a closed TextWriter...

Here is the method that I'm using to wait for packets to arrive:

public void WaitForPackets()
        {
            while (true)
            {                
                byte[] data = client.Receive(ref receivePoint);
                AddTextToTextBox(System.Text.Encoding.ASCII.GetString(data));
            }
        }

Is anyone familiar with this exception?

covertx,

The str value you are passing to the delegate needs to be done a little differently.

Invoke is an eventhandler type. That means it takes Sender and Params as the second argument. just like all other event handlers in c#. Params is an object array (like args).

In your case you only need one parameter passed, but as far as the engine is concerned, it still has to be a list of params as an object array. So Try this.

this.Invoke(new AddnewText(AddTextToTextBox), new object[] {str});

BTW, The Delegate you defined will cast the object array into the parameter slots in the delegatel... So you do not need to do any additional casting... It will come back into the target method already cast (back to string in your case).

-- Jerry

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.