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) {..}
1
  • You said you ignored BeginXXX and EndXXX in APM model because you didn't want to block main thread at all. Where do you get this fact? The APM model is actually called EAP, and it is is not blocking main thread at all because it is asynchronous: docs.microsoft.com/dotnet/standard/…
    – eriawan
    Aug 3, 2020 at 7:51

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.