views:

624

answers:

1

I can't figure out why this is.

I have a connect method that works fine:

public void Connect()
{
    _client.BeginConnect(new AsyncCallback(this.ConnectCallback), _client);
}

public void ConnectCallback(IAsyncResult asyncResult)
{
    ServerClient callback = null;

        callback = (ServerClient)asyncResult.AsyncState;
        callback.EndConnect(asyncResult);

        Program.IMMainForm.BeginInvoke(new frmMain.ConnectionEstablishedNotification(Program.IMMainForm.ConnectionEstablished));

This works totally fine. I pretty much copied and pasted this code for my Send method:

public void Send(string code, string data)
{
    _client.BeginSendToServer((code + data), new AsyncCallback(this.SendCallback), _client);
}


public void SendCallback(IAsyncResult asyncResult)
{
    ServerClient callback = null;

        callback = (ServerClient)asyncResult.AsyncState;
        callback.EndConnect(asyncResult);
}

However it errors on the EndConnect line with the error

"Async End called with an IAsyncResult from a different Begin method. Parameter name: result"

saying

A first chance exception of type 'System.ArgumentException' occurred in mscorlib.dll

I'm not 100% on async stuff so is there something obvious I am doing wrong?

+3  A: 

You should be calling EndSendToServer, not EndConnect.

Generated async methods are paired with the Begin and End prefixes; you begin the async operation with one method and end it with the other.

Ben M