Timeout for Action in Parallel.ForEach iteration

前端 未结 3 2238
[愿得一人]
[愿得一人] 2021-02-14 22:10

I have something similar to this in my code:

Parallel.ForEach(myList, new ParallelOptions { MaxDegreeOfParallelism = 4 }, item =>
{
    Process(item);
});
         


        
3条回答
  •  时光取名叫无心
    2021-02-14 22:56

    I ended up combining both options. It works but I don't know if this is the proper way to do this.

    Solution:

            Parallel.ForEach(myList, new ParallelOptions { MaxDegreeOfParallelism = 4 }, item =>
            {
                    var tokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(30));
                    var token = tokenSource.Token;
    
                    Task task = Task.Factory.StartNew(() => Process(item, token), token);
                    task.Wait();
            });
    

    and in Process() I check for cancellation multiple times:

        private void Process(MyItem item, CancellationToken token)
        {
            try
            {
                if (token.IsCancellationRequested)
                    token.ThrowIfCancellationRequested();
    
                ...sentences
    
                if (token.IsCancellationRequested)
                    token.ThrowIfCancellationRequested();
    
                ...more sentences
    
                if (token.IsCancellationRequested)
                    token.ThrowIfCancellationRequested();
    
                ...etc
            }
            catch(Exception ex)
                Console.WriteLine("Operation cancelled");
    

提交回复
热议问题