Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7633581
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T06:55:31+00:00 2026-05-31T06:55:31+00:00

It seems that finally block doesn’t execute if it other than main thread execute

  • 0

It seems that finally block doesn’t execute if it other than main thread execute code. Is it possible to force execute finally in that case?

Environment: VS 2010, .Net Framework 4.0.3

class Program
{
    static void Main(string[] args)
    {
        var h = new AutoResetEvent(false);

        ThreadPool.QueueUserWorkItem(
            obj => TestProc(h));

        h.WaitOne();
    }

    private static void TestProc(EventWaitHandle h)
    {
        try
        {
            Trace.WriteLine("Try");
            h.Set();
        }
        catch(Exception)
        {
            Trace.WriteLine("Catch");
        }
        finally
        {
            Thread.Sleep(2000);
            Trace.WriteLine("Finally");
        }
    }
}

Update:

I found mentions and explanation about that case in MSDN:

ThreadAbortException Class
http://msdn.microsoft.com/en-us/library/system.threading.threadabortexception.aspx

When a call is made to the Abort method to destroy a thread, the
common language runtime throws a ThreadAbortException.
ThreadAbortException is a special exception that can be caught, but it
will automatically be raised again at the end of the catch block. When
this exception is raised, the runtime executes all the finally blocks
before ending the thread
. Because the thread can do an unbounded
computation in the finally blocks or call Thread.ResetAbort to cancel
the abort, there is no guarantee that the thread will ever end. If
you want to wait until the aborted thread has ended, you can call the
Thread.Join method. Join is a blocking call that does not return until
the thread actually stops executing.

Note:

When the common language runtime (CLR) stops background threads after
all foreground threads in a managed executable have ended, it does not
use Thread.Abort. Therefore, you cannot use ThreadAbortException to
detect when background threads are being terminated by the CLR.


Foreground and Background Threads http://msdn.microsoft.com/en-us/library/h339syd0.aspx

When the runtime stops a background thread because the process is shutting down, no exception is thrown in the thread. However, when threads are stopped because the AppDomain.Unload method unloads the application domain, a ThreadAbortException is thrown in both foreground and background threads.


So why at the end of application CLR doesn’t use AppDomain.Unload method for unloading the application domain before end (kill) of main process?
Because http://msdn.microsoft.com/en-us/library/system.appdomain.unload.aspx:

When a thread calls Unload, the target domain is marked for unloading.
The dedicated thread attempts to unload the domain, and all threads in
the domain are aborted. If a thread does not abort, for example
because it is executing unmanaged code, or because it is executing a
finally block, then after a period of time a
CannotUnloadAppDomainException is thrown in the thread that originally
called Unload. If the thread that could not be aborted eventually
ends, the target domain is not unloaded. Thus, in the .NET Framework
version 2.0 domain is not guaranteed to unload
, because it might not
be possible to terminate executing threads.

Conclusion: In some cases I need to consider if will my code be executing in background or foreground thread? Is it possible that my code will not finished before application main thread ends all work?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-31T06:55:32+00:00Added an answer on May 31, 2026 at 6:55 am

    Your code is running in a background thread. When you set the AutoResetEvent, your single foreground thread terminates (as you reach the end of the Main method) and the process is torn down “immediately”.

    In fact, I think it likely that your finally block starts executing, but as the first thing you do is sleep for two seconds, the process quits before it gets to your WriteLine call.

    If your Main method were still running, or any other foreground thread were keeping the process alive, you’d see your finally block complete as normal. This isn’t really a matter of “finally on other threads” – it’s a matter of “the process only stays alive while there are foreground threads”.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

So that IO doesn't block the UI thread in my Android app, I'm trying
Inspired from the other topic , I wrote this code which simulates a finally
Using a try-catch-finally construction to retrieve a database record, it seems that I need
Seems that requirements on safety do not seem to like systems that use AI
Seems that even after unchecking the option in the PyDev/Debug preferenecs pane to launch
It seems that a List object cannot be stored in a List variable in
It seems that it is impossible to capture the keyboard event normally used for
It seems that Silverlight/WPF are the long term future for user interface development with
It seems that most of the installers for Perl are centered around installing Perl
It seems that anyone can snoop on incoming/outgoing .NET web service SOAP messages just

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.