2010-03-04 29 views
23

Sto tentando di chiudere la risposta utilizzando Context.Response.End ma si riceve l'errore "Thread was being aborted".Context.Response.End() e il thread è stato interrotto

Come chiudere correttamente la risposta senza attivare un'eccezione?

try { 
    Context.Response.Clear(); 
    Context.Response.ContentType = "text/html"; 
    //Context.Response.ContentType = "application/json"; 
    JsonObjectCollection collection = new JsonObjectCollection(); 
    collection.Add(new JsonNumericValue("resultcode", 1)); 
    collection.Add(new JsonStringValue("sourceurl", exchangeData.cUrl)); 
    collection.Add(new JsonStringValue("filename", fileName)); 
    collection.Add(new JsonStringValue("filesize", fileSize)); 
    collection.Add(new JsonStringValue("fileurl", Common.GetPDFURL + outputFileName)); 
    JsonUtility.GenerateIndentedJsonText = true; 
    Context.Response.Write(collection); 
    try { 
    Context.Response.End(); 
    } catch (ThreadAbortException exc) { 
    // This should be first catch block i.e. before generic Exception 
    // This Catch block is to absorb exception thrown by Response.End 
    } 
} catch (Exception err) { 

} 

risolto da solo, il codice dovrebbe assomigliare

try { 
    Context.Response.End(); 
} catch (ThreadAbortException err) { 

} 
catch (Exception err) { 
} 
+0

Avete il respose.end all'interno di un blocco try trucco? – Andrew

+0

Ho aggiunto il mio codice. Sì, ho aggiunto Context.Response.End(); all'interno di Try/catch block e come vedi c'è il blocco Try/catch principale che è anche un errore di cattura "Thread was aborted". – Tomas

+1

Risolto da me, il codice dovrebbe essere simile provare {} catch (err ThreadAbortException) {} catch (Exception err) {} – Tomas

risposta

26

C'è un motivo specifico non si utilizza context.ApplicationInstance.CompleteRequest() invece?

questo metodo corto circuito la pipeline ASP.NET (tranne che per l'evento EndRequest) senza gettare il ThreadAbortException in modo non sarà necessario l'extra blocco try/catch, e potrete anche sperimentare una migliore performance.

+1

[articolo di MSDN che spiega questo] (http: // support .microsoft.com/kb/312629/it-it) – snumpy

+1

Ho appena provato questo (un po 'tardi alla festa). Non sembra funzionare correttamente: certamente non ha gettato l'eccezione Response.End() ha gettato, ma ha fatto sì che il contenuto della pagina .aspx venisse aggiunto a ciò che avevo già scritto su Response.OutputStream . Un'opzione potrebbe essere quella di non avere contenuto nel file .aspx ma l'ho usato per visualizzare il contenuto per gli errori. – Kate

2

Errore: il thread è stato interrotto. a System.Threading.Thread.AbortInternal() in System.Threading.Thread.Abort (Object info_stato) a System.Web.HttpResponse.End()

Questo errore si verifica soprattutto se si utilizza Response.End, Response.Redirect o Server.Transfer

Causa: il metodo Response.End termina l'esecuzione della pagina e sposta l'esecuzione all'evento Application_EndRequest nella pipeline eventi dell'applicazione. La riga di codice che segue Response.End non viene eseguita.

Questo problema si verifica nei metodi Response.Redirect e Server.Transfer poiché entrambi i metodi chiamano Response.End internamente.

Risoluzione/Soluzione:

È possibile utilizzare un'istruzione try-catch per intercettare questa eccezione

o

Per Response.End, chiamare il metodo HttpContext.Current.ApplicationInstance.CompleteRequest invece di Response.End per ignorare l'esecuzione del codice all'evento Application_EndRequest. Per Response.Redirect, utilizzare un overload, Response.Redirect (String url, bool endResponse) che passa false per il parametro endResponse per sopprimere la chiamata interna a Response.End. Ad esempio: ex: Response.Redirect ("nextpage.aspx", false); Se si utilizza questa soluzione alternativa, viene eseguito il codice che segue Response.Redirect. Per Server.Transfer, utilizzare invece il metodo Server.Execute.

7

Prova response.OutputStream.Close(); anziché response.End(); Aiuterà!

+0

ha funzionato per me! Grazie! – Flea

0

vi consiglio questa soluzione:

  1. Non utilizzare Response.End();

  2. Dichiarare questo globale var: bool isFileDownLoad;

  3. Subito dopo (risposta.Write (sw.ToString());) set ==> isFileDownLoad = true;

  4. ignorare la Render come:

    /// /// AEG: Molto importante per gestire l'eccezione filo interrotto /// /// override void protetto Render (HtmlTextWriter w) { if (! IsFileDownLoad) base.Render (w); }

0

Oppure è possibile posizionare il context.Response.End() all'interno di un blocco, infine. In questo modo non dovrai preoccuparti di ThreadAbortException indesiderato, né ignorare la reale ThreadAbortException (che è male). Inoltre, non ignorerai le fasi del gasdotto.

try 
{ 
    context.Response.ContentType = "application/json"; 
    context.Response.ContentEncoding = Encoding.UTF8; 

    if (NotAuthorized()) 
    { 
     context.Response.StatusCode = (int)System.Net.HttpStatusCode.Unauthorized; 
     return; 
    } 

    context.Response.Write(MakeJsonStuff()); 
} 
catch (Exception ex) 
{ 
    LogException(ex); 

    context.Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError; 
    context.Response.Write(MakeJsonError(ex)); 
} 
finally 
{ 
    context.Response.End(); 
} 
0

Questo mi ha aiutato a gestire Thread was being aborted eccezione,

try 
{ 
    //Write HTTP output 
    HttpContext.Current.Response.Write(Data); 
} 
catch (Exception exc) {} 
finally { 
    try 
    { 
     //stop processing the script and return the current result 
     HttpContext.Current.Response.End(); 
    } 
    catch (Exception ex) {} 
    finally { 
     //Sends the response buffer 
     HttpContext.Current.Response.Flush(); 
     // Prevents any other content from being sent to the browser 
     HttpContext.Current.Response.SuppressContent = true; 
     //Directs the thread to finish, bypassing additional processing 
     HttpContext.Current.ApplicationInstance.CompleteRequest(); 
     //Suspends the current thread 
     Thread.Sleep(1); 
    } 
    } 

se si utilizza il seguente codice seguente invece di HttpContext.Current.Response.End(), si otterrà Server cannot append header after HTTP headers have been sent eccezione.

  HttpContext.Current.Response.Flush(); 
      HttpContext.Current.Response.SuppressContent = True; 
      HttpContext.Current.ApplicationInstance.CompleteRequest(); 

Un'altra Fix che ho trovato è Thread.BeginCriticalRegion();

try 
{ 
    //Write HTTP output 
    HttpContext.Current.Response.Write(Data); 
    } catch (Exception exc) {} 
    finally { 
    try { 
    //Notifies a host that execution is about to enter a region of code in which the effects of a thread abort or unhandled exception might jeopardize other tasks in the application domain. 
    Thread.BeginCriticalRegion(); 
    HttpContext.Current.Response.End(); 
     } catch (Exception ex) {} 
    finally { 
    //Sends the response buffer 
    HttpContext.Current.Response.Flush(); 
    // Prevents any other content from being sent to the browser 
    HttpContext.Current.Response.SuppressContent = true; 
    //Directs the thread to finish, bypassing additional processing 
    HttpContext.Current.ApplicationInstance.CompleteRequest(); 
    Thread.EndCriticalRegion(); 
     } 
    } 

Speranza che aiuta

Problemi correlati