简体   繁体   中英

How to detect which thread is holding the application from shut down in .NET

I'm just wondering if there any way to detect an alive thread that is holding the application from shutting down properly in C#/.Net. Which means that after users close the application, its instance is still visible in the task manager.

i would run the program in debug mode in visual Studio. on closing GUI if the program is still running, i will pause my debug mode, this will tell where my program is at. For advance view when running your program in debug mode, goto DEBUG>Windows>Thread Window. This will show all the the threads your program has spawned. may be this can help you .

You will get a window like this http://mscerts.programming4.us/image/201307/Debugging%20with%20Visual%20Studio%202010_7.jpg

for more information how to used Thread Window and how to debug multithreaded applications

1) How to Used Thread Window

2) How to Debug a MultiThreaded Application

3) Debug Multithreaded Applications in Visual Studio

You should be able to hit pause and it take you to section of code that is running.

Another option is to add break points at the end of functions and see which one doesn't get hit...

You may save all created threads in a container such as List and check IsAlive and ThreadState properties during exiting.

Another option to not care about holding threads is to set the IsBackground property to false to them. Also if you use ThreadPool or Task your threads are always background threads and it's recommended to use these classes instead of creating Thread manually.

(By the way, more information about your application type and reasons of exiting would be useful.)

Even I have a list of active threads, some of them cannot be traced because their call stacks are not available.

In addition, I just want to shut down the application gracefully. So I have made the following changes to my application.

1. In App.StartUp()

Set the shut down mode

protected override void OnStartup(StartupEventArgs e)
        {
              Current.ShutdownMode = ShutdownMode.OnMainWindowClose;
}
  1. When users click a close button, call the following function

    Application.Current.Shutdown();

Cheers.

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