1

I have a legacy code library that provides the following method signature

void DoWork(IEnumerable<IMessage> message,
                         Action<IEnumerable<IMessage>, Exception> onErrorCallBack,
                         Action<IEnumerable<IMessage>> onCompletionCallBack);

When I call this method in my code, I am unable to wait for the onErrorCallBack and starts executing the next line of code. Is there a way to wait for the callbacks to arrive and then proceed to the next line? This is getting more worst if i fire this method inside a parallel for loop. The loop continues without waiting for the callback and results in many calls bogging down my system resources. Any respite?

  • What if there's no error and `onErrorCallback` doesn't get called? – phuzi Jan 17 '22 at 08:22
  • You can "wrap" this call to use it with async/await - I have marked your question as a duplicate of another one which describes this technique. If this solution is not applicable to your situation, just explain why and I will remove the duplicate lock. – Heinzi Jan 17 '22 at 08:24
  • @phuzi: If there is no error, the success block is called. Error block is optional, to be called only when the called method throws an exception. – Arun Prakash Nagendran Jan 17 '22 at 08:25
  • @Heinzi: The other thread describes the approach with one callback. Can that be extended to cater to multiple callbacks? – Arun Prakash Nagendran Jan 17 '22 at 08:33
  • @ArunPrakashNagendran: Sure, just make it a `TaskCompletionSource<(IEnumerable, Exception)>`. In the error case, set the exception, in the success case, set it to null. – Heinzi Jan 17 '22 at 09:55
  • @Heinzi: Thank you. When I tried it, I was missing the paranthesis ( ) and it was throwing error. – Arun Prakash Nagendran Jan 17 '22 at 11:03
  • Not sure about "multiple" callbacks, but since the other one is an indication of error, the `onErrorCallback` would be `(_, e) => t.TrySetException(e);` (where `t` is a `TaskCompletionSource>`). – madreflection Jan 17 '22 at 15:30

0 Answers0