Wait a few callbacks

I use a library that makes asynchronous calls, and when the response is returned, the callback method is called with the result. This is a simple example, but now I find an obstacle. How to make several calls to asynchronous methods and wait (without blocking) for them? When I receive data from the entire service, I would like to call my own callback method, which will receive two (or more) values ​​returned by the async method.

What is the right scheme to follow here? By the way, I can't change the library to use TPL or anything else ... I need to live with it.

public static void GetDataAsync(Action<int, int> callback) { Service.Instance.GetData(r1 => { Debug.Assert(r1.Success); }); Service.Instance.GetData2(r2 => { Debug.Assert(r2.Success); }); // How do I call the action "callback" without blocking when the two methods have finished to execute? // callback(r1.Data, r2.Data); } 
+6
source share
2 answers

What you want is something like CountdownEvent . Try this (if you are using .NET 4.0):

 public static void GetDataAsync(Action<int, int> callback) { // Two here because we are going to wait for 2 events- adjust accordingly var latch = new CountdownEvent(2); Object r1Data, r2Data; Service.Instance.GetData(r1 => { Debug.Assert(r1.Success); r1Data = r1.Data; latch.Signal(); }); Service.Instance.GetData2(r2 => { Debug.Assert(r2.Success); r2Data = r2.Data; latch.Signal(); }); // How do I call the action "callback" without blocking when the two methods have finished to execute? // callback(r1.Data, r2.Data); ThreadPool.QueueUserWorkItem(() => { // This will execute on a threadpool thread, so the // original caller is not blocked while the other async run latch.Wait(); callback(r1Data, r2Data); // Do whatever here- the async have now completed. }); } 
+6
source

You can use Interlocked.Increment for every asynchronous call you make. When you're done, call Interlocked.Decrement and check for null; if null, call your own callback. You will need to store r1 and r2 outside the callback delegates.

+2
source

Source: https://habr.com/ru/post/917065/


All Articles