c# - Running multiple Threads sequentially? -


Maybe my view is wrong, do not hesitate to correct me.

I have the following method of service:

  Public Zero for PublishPriceChange () {for (int i = 0; I & lt; 200; i ++) {Task .Run ((= = gt; {int j = i; lock (_locker) {TransformPrices (_quotes); PriceChangeEventArgs e = new PriceChangeEventArgs (_quotes); PriceChanged (this, e);}}); }}  

_quotes is the starting price of the day and TransformPrices () These calls vary slightly on each call Illustrates changes during the day. So these tasks have to be run in a gradual manner.

Although running on a thread pool means that every task is running in parallel and is no longer in the sequence.

Obviously I could run them to get the necessary effect without much anticipation. But since the calculation takes some time, it will be good to keep the tax service responsible for these tasks in its background.

Maybe I can not use the continuation (awaiter) but for sure how to chain it all the way through. any advice?

So, you want to change the values ​​gradually. Your goal seems to be keeping the service responsible (i.e., calling threads free to do other work).

Why not use the work to run the whole loop?

  Work PublishPriceChange () async Public {wait Task.Run (() => {lock (_locker) {(int i = 0; I & lt; 200; i ++) {TransformPrices (_quotes); PriceChangeEventArgs e = new PriceChangeEventArgs (_cotes); value-packed (this, e);}}}); }  
  • You can wait for the task, you probably do not want a fire-and-forgotten behavior ().
  • If you were using the lock to run the sequence to ensure the loop, you can remove it.
  • Otherwise, there is a possibility that will be called PublishPriceChange second time, instead of locking 200 times once, you will minimize over the ground due to the context switch
- Before the first call completes, the lock goes out of the lock.

Comments