Throw an exception to a C # stream

I have thread. So, after I see an example link text

ThreadStart _threadStart = new ThreadStart(delegate()
{
       try
       {
           threadFunction(httpContext);
       }
       catch (Exception ex)
       {
           throw ex;
       }
 });
 Thread _thread = new Thread(_threadStart);
  _thread.Start();

when an exception occurs, it will not be reinserted into the thread that started it. So what am I doing wrong or how to do it?

Note: thanks to all the comments in the advanced

+5
source share
6 answers

An exception will be thrown, but this will only end the thread. The exception is not thrown to the thread that started it.

+7
source

I think the point is to understand that the exceptions that occur in the thread will not be passed to the calling thread for processing.

, , :

private static void RebelWithoutACause()
{
    throw new NullReferenceException("Can't touch this!");
}

, , , , try/catch:

private static void Main(string[] args)
{
    try
    {
        var thread = new Thread(RebelWithoutACause);
        thread.Start();
        thread.Join();
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

, , , catch, , , .

, , . , , .

+6

, ? , , , AppDomain.CurrentDomain.UnhandledException ( , , , , - . ).

, , :

, , .

/ (), .

+2

, , , . , ( , ), , .

, , , .:)

+1

- :

   const int numThreads = 8;
   Thread[] threads = new Thread[numThreads];
   Exception[] threadsExceptions = new Exception[numThreads];
   for (int i = 0; i < numThreads; i++) {
       threadsExceptions[i] = null;
       int closureVariableValue = i;
       ThreadStart command = () =>
       {
           try
           {
               throw new ArgumentException("thread_" + closureVariableValue + " exception");
           }catch(Exception any)
           {
               threadsExceptions[closureVariableValue] = any;
           }
       };
       threads[i] = new Thread(command);
       threads[i].Start();
   }
   for(int i = 0; i < numThreads; i++)
   {
       threads[i].Join();
       if (threadsExceptions[i] != null)
       {
           throw threadsExceptions[i];
       }
   }
0

All Articles