0

I am new to multi-threading. I have a Parallel.For loop working great!

I do have a cancellation token.

Our DBA just happened to notice that I had a lot of active threads (I was testing and using the tool in a way it will not be used in production).

Anyway, I started looking for ways to clean up the threads after processing and cannot find anything. Do I need to do clean up other than cts.Cancel?

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
DaSy
  • 23
  • 3
  • 1
    (hint: when doing stuff where you mostly _wait_ for other systems, like database calls, best use async/await instead of threads.) can you please provide more context for your question? for example - the code? usually, threads aren't something you have to clean up after. probably you're forgetting some `using` statements for `Disposable` resources. i recommend [taking the tour](https://stackoverflow.com/tour), as well as reading [how to ask a good question](https://stackoverflow.com/help/how-to-ask) and [what's on topic](https://stackoverflow.com/help/on-topic). – Franz Gleichmann Nov 15 '21 at 16:23
  • My development network is not connected to the internet so it is hard to copy code. I am running the process in a dll called by a queuebackgroundworkitem. It is very basic var po = new ParallelOptions(); var cts = new CancellationTokenSource(); po.CancellationToken = cts.Token; Parallel.For(o, page.Count, po, index => { CreateObject(page[index]); }); cts.Cancel(); – DaSy Nov 15 '21 at 16:26
  • please actually _do read_ the articles i've linked to - and **edit** your question to provide additional information, while taking care of proper formatting. and make sure it contains _enough_ information. we can't spot problems in code you didn't provide. – Franz Gleichmann Nov 15 '21 at 16:35

1 Answers1

1

The Parallel.For/Parallel.ForEach methods have the nasty habit of saturating the ThreadPool when the MaxDegreeOfParallelism option is not configured. This causes the ThreadPool to start injecting new threads in the pool, with a frequency of around one new thread per second. To keep the ThreadPool under control, just make sure that you have configured the parallel loop with a reasonable MaxDegreeOfParallelism, like Environment.ProcessorCount:

var po = new ParallelOptions() { MaxDegreeOfParallelism = Environment.ProcessorCount };

Configuring the CancellationToken option is only needed if you want to cancel the loop while it's running. Using it for cleaning-up purposes is unlikely to have any effect.

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104