views:

30

answers:

1

It states in the MSDN documentation that:

at the very minimum, your state parameter must contain the connected or default Socket being used for communication. Since you will want to obtain the received data within your callback method, you should create a small class or structure to hold a read buffer, and any other useful information. Pass the structure or class instance to the BeginReceive method through the state parameter.

However I am calling the BeginRecieve and passing an instance method as my AsyncCallback:

class MyClass
{
    private Socket mysocket;

    private void callback(IAsyncResult Result)
    {
        Record record = this.mysocket.EndReadRecord(Result);
        // Do things
        this.mysocket.BeginReadRecord(new AsyncCallback(callback), null);
    }

    // Other methods
}

With the assumption that mysocket is only set once (during the constructor), is there any need to pass my socket as part of the state parameter, or is it safe to use the instance field mysocket?

+2  A: 

If you only touch it during the callback, or basically in isolated ways, you will be safe.

That tends to be the way I handle delegates, define a delegate variable outside of method scope to use it during a callback.

Adam