2

I am looking to implement the callback pattern with error handling such that error is caught and pass to the callback code with the response. Since I am using .NET 3.5, I cant use Task (TAP) pattern which provides us with t.Result and t.Exception properties. I tried some googling for best practices and ended up with the Begin/End APM model. Since I dont want to block the main thread, I ignored this model.

So here is a list of design ideas I currently have. I would love to hear which approach is the best/popular way to implement the callback pattern

  1. Place the Exception instead the Result object directly. I didnt like this method very much since it changes the definition of Result object
void OperationNameAsync(Action<Result> callback) {..}
void OperationCallback(Result result) {
    if (result.Exception != null) {
        // successful result
    } else {
       // exception handling
    }
}
  1. Use two parameters in the callback - Result, Exception. I got this idea from Javascript callbacks.
void OperationNameAsync(Action<Result, Exception> callback) {..}
  1. Use a generic wrapper object say Response which contains Result & Exception. Trying to mimic what Task object achieves.
class Response {
   T Result;
   Exception Exception;
}
void OperationNameAsync(Action<Response<Result>> callback) {..}
  1. Use separate callbacks for OnError and OnSuccess
void OperationNameAsync(Action<Response> onSuccessCallback, Action<Exception> onErrorCallback) {..}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.