Asynchronous call for a delegate in a loop

I need to call the asynchronous number of delegates for the same function. The question is, how should I handle the callback function? we have a pair of delegates that work so that CallbackMethod does not mean that all async delegates are complete.

AsyncMethodCaller c = new AsyncMethodCaller(instance.dummyMethod); for (int i = 0; i < 100; i++) { IAsyncResult res = c.BeginInvoke(5000, out dummy, new AsyncCallback(CallbackMethod), "executed on thread {0}, with result value \"{1}\"."); } 
+5
source share
2 answers

I would like to consider using Task with TPL .

 var task1 = Task.Run(() => instance.dummyMethod) .ContinueWith((completedTask) => Console.WriteLine("Each callback here. Result: " + completedTask.Result)); // Blocks calling thread until all tasks are done. Task.WaitAll(new [] { task1, task2 }); 

WaitAll all ensures that all WaitAll are executed before the main thread continues. The above allows you to implement individual callbacks.

Alternatively, use a single callback when All asynchronization methods are complete:

 Task.Factory.ContinueWhenAll(new [] { task1, task2 }, (allTasks) => Console.WriteLine("Callback when all are done.")); 
0
source

I would be inclined to use the Microsoft Reactive Framework (NuGet "Rx-Main") for this, as that would be a lot easier.

Here is the code:

 var query = from n in Observable.Range(0, 100) from dummy in Observable.Start(() => instance.dummyMethod()) select dummy; query .Subscribe( dummy => { Console.WriteLine(dummy.ToString()); }, () => { Console.WriteLine("Done."); }); 

The .Subscribe method has a callback for each dummy value received, as well as a β€œmade” callback when all values ​​are returned.

The request is executed for several threads automatically for you.

0
source

All Articles