/// Asynchronous score request api method. /// Most work is pushed off to an OnConnect callback. public void RequestScoresAsync(string level, Action <ScoresResponse, ServerException> callback) { // Ensure arguments are valid if (level == null) { throw new ArgumentNullException(); } // external callback and argument container RequestScoresState state = new RequestScoresState(level, callback); // make the async connection with the onconnect callback ConnectAsync(new AsyncCallback(RequestScoresOnConnectCallback), state); }
/// OnConnect callback, the bulk of the work is handled here. void RequestScoresOnConnectCallback(IAsyncResult ar) { RequestScoresState state = (RequestScoresState)ar.AsyncState; // the arguments for the external callback ServerException error = null; ScoresResponse scores = new ScoresResponse(state.level); // handle being unable to connect if (!client.Connected) { error = new ServerException("Unable to connect"); } else { try { // form a request message and send it to the server string request = ScoresRequest.ToJson(state.level); WriteLine(request); // get a response from server and convert back to an object string response = ReadLine(); scores = ScoresResponse.FromJson(response, state.level); } catch (ServerException e) { error = e; } } // report back to user if (state.callback != null) { state.callback.Invoke(scores, error); } // note: even if connection failed, clean up is still necessary DisconnectAsync(ar); }