c# - How do I throw an Exception from inside a Parallel.ForEach loop? -
i have parallel.foreach
loop downloads files so:
try { var paralleloptions = new paralleloptions(); paralleloptions.maxdegreeofparallelism = 8; int failedfiles = 0; parallel.foreach(filestodownload, paralleloptions, tile => { bool downloaded = downloadtile(file); if (downloaded) { //downloaded :) } else { failedfiles++; if (failedfiles > 10) { throw new exception("10 files failed download. failing download"); } } paralleloptions.cancellationtoken.throwifcancellationrequested(); }); } catch (exception ex) { throw; //this throws main method cancels program }
and wondering correct way throwing exception
inside parallel.foreach
method? in instance think going see exception thrown 8 times first exception thrown.
what correct way throw exceptions in parallel.foreach
loops?
first, better use interlocked.increment(ref failedfiles)
instead of failedfiles++
. otherwise can happen have 10-15 failures, end counter value 7-8, because of lack of cache synchronization , effect of compiler/jitter optimizations. loop of program might throw more exceptions, @ end aggregated single aggregateexception
, , outter catch()
receive single exception instance. if not want more exceptions in aggregateexception
, can use ==
instead of >
if (interlocked.increment(ref failedfiles) == 10)
when exception thrown inside loop, parallel.foreach
prevents other iterations start, waits running iterations finish, aggregates exceptions caught, packs aggregateexception
, throws single instance. means in case single exception prevent further downloads.
Comments
Post a Comment