darklordzz
darklordzz

Reputation: 19

Solve my Object Disposed Exception

Hello can any1 tell me where to try catch this exception or solve it. Whenver i close my receive handle, if i still recieved some data, it comes up with this error.

public partial class Form1 : Form
{
    SerialPort sp;
    IAsyncResult recv_result;
    string buffer;

    private delegate string ReadLine_Delegate();
    private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            sp = new SerialPort("COM8", 9600);
            sp.Open();
            sp.ReadTimeout = 50000;
            sp.NewLine = "\n\r\0";

            ReadLine_Delegate x = new ReadLine_Delegate(sp.ReadLine);

            recv_result = x.BeginInvoke(new AsyncCallback(ReadLine_Callback),
                                        x);
        }
        catch (Exception ex)
        {

        }
    }

    private void ReadLine_Callback(IAsyncResult iar)
    {
          ReadLine_Delegate y = (ReadLine_Delegate)iar.AsyncState;
          try
          {
              buffer = y.EndInvoke(iar);
          }
          catch
          {
              MessageBox.Show("Error");
              return;
          }
          ListBoxAdd(buffer);
          buffer = "";
          recv_result = y.BeginInvoke(new AsyncCallback(ReadLine_Callback), y);
    }

    private void disconnectButton_Click(object sender, EventArgs e)
    {
        recv_result.AsyncWaitHandle.Close();
        sp.Close();

    }
}

Upvotes: -4

Views: 1023

Answers (2)

Volem
Volem

Reputation: 636

lock block would probably solve your problem inside the ReadLine_Callback. Also check the IAsyncResult.IsCompleted status.

lock(lockerobject)
{
   // your handler logic.
}

Upvotes: 0

dlev
dlev

Reputation: 48596

I'm pretty sure what's happening is that you are executing the blocking ReadLine() call on another thread (via your delegate's BeginInvoke) but then calling Close() on the SerialPort while it is still in the ReadLine() call. When data comes in on the now closed (and thus disposed) port, the exception is thrown.

The usual solution is to not close the port until any outstanding reads have finished. You may need to set a timeout on the read in order to ensure it will return at some point. See the example here for more info.

Upvotes: 1

Related Questions