Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Parallel Loop State (feature request) #17

Open
sallgeud opened this issue Oct 17, 2017 · 1 comment
Open

Parallel Loop State (feature request) #17

sallgeud opened this issue Oct 17, 2017 · 1 comment

Comments

@sallgeud
Copy link

Current Parallel.ForEach passes a loop state to any method calls. This can be valuable as any break may necessitate immediate stoppage of the loop, which can be done by calling loopstate.Stop().

@kind-serge
Copy link
Member

kind-serge commented Jan 20, 2018

I would challenge you with such feature request and ask to think about using CancellationToken which is the recommended thing to use with asynchronous operations. Here is an example:

public IAsyncEnumerable Enumerate() =>
  new AsyncEnumerable(async yield =>
  {
    var result1 = await FooAsync(yield.CancellationToken);
    await yield.ReturnAsync(result1);

    var result2 = await BarAsync(yield.CancellationToken);
    await yield.ReturnAsync(result2);
  });
  
public async Task ProcessAsync(CancellationToken cancellationToken)
{
  var innerCts = new CancellationTokenSource();
  var combinedCancellationToken = CancellationTokenSource.CreateLinkedTokenSource(
    cancellationToken, innerCts.Token);
  
  await Enumerate().ForEachAsync(async item =>
  {
    if (...) // cancellation-control logic
      innerCts.Cancel(); // cancels all associated async tasks and ForEachAsync 
                         // will throw OperationCanceledException
  },
  cancellationToken: combinedCancellationToken);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants