A
A
Alex Wells2015-10-25 17:03:19
C++ / C#
Alex Wells, 2015-10-25 17:03:19

Async in C# loop?

Hello. There is a foreach loop that collects data and calls a function with that data. But this function takes a long time, I would like to run the functions for all the data from the loop at once. Actually, I read about asynchrony, but I didn’t really drive it, besides, I don’t know how it will work with the cycle and in general what can happen. It should work like this:
1) While(true) thread, with a delay after execution of 1 second
2) Data is taken from one API.
3) Are processed, the cycle turns out.
4) In the loop, an asynchronous function is called for each data cell.
5) Without waiting for the processing of f-th, wait 1 second and send the request to the API again.
6) Everything from the beginning, while not allowing the call f-th with data that has not yet been processed from the previous request
All the code is already there, only asynchrony remains. Who knows how to do it right? F-I returns nothing.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman, 2015-10-26
@yarosroman

Task.Run

V
Vitaly Pukhov, 2015-10-26
@Neuroware

the easiest way is to use parallel for each , but there are downsides, for example, it is undesirable to change the collection during processing.
a better way is to build a queue, that is, pull out objects from the list and throw them into another list, and hang handlers on another list, 1 for each element of the list. As each handler is executed, overwrite the element by 1 from the common heap.
The first way is simple, you need to replace a couple of lines, the second way is better, but more complicated. On it do all normal servers of processing.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question