简体   繁体   中英

c# check of threadpool and other threads

Basically - we write unit tests. Sometimes those unit tests start threads - and often start tasks on the threadpool. If something goes wrong in a background thread - it can causes strange problems with future tests. What we want to do on the base teardown of each test is basically

  • check what threads are running
  • fail the test if any are running that shouldn't be

now, for normal threads, we can just enumerate before hand, and compare to afterwards - which is fine. The threadpool messes things up - because there may have been many new threads validly created, which are just waiting around doing nothing - which is fine. It's NOT fine if the test has left something running. Remember also - I am not writing the tests or code being tested - I'm writing the underlying libraries that try to ensure that no one else can screw things up, however hard they try - so I can't try using my own implementation of a threadpool or anything like that, because I can't be sure someone is not using the standard one.

Can anyone think of a way either to tell what threads are out there owned by the threadpool, and whether they are idle? My next step is to crawl through the private variables with reflection looking - but I'm hoping someone has a better way?

Thanks, Darren

I infer you are using fire-and-forget style threads/tasks/workitems. If you weren't you would not have the problem that they continue running after the test.

I consider fire-and-forget to be a problematic pattern because even outside of unit tests (in production) you never want to forget about errors. Also, in ASP.NET you are not guaranteed that background work will ever complete because the worker process can shut down after all pending HTTP requests have been processed and before the background work is done.

So I recommend that you audit your code and switch all concurrency to the new Task -based model. That allows you to track completion. It also allows you to wait for completion and propagate errors.

You could add all started tasks to a list (maybe using a custom TaskScheduler , maybe manually). When the unit test shuts down you do a Task.WaitAll on the contents of that list. That guarantees you completion.

In any case the threadpool does not allow you to listen for enqueued items or for completion. You need to solve this in your own code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM