Как обрабатывать поток был прерван Exception vb.net/C#?

Я видел несколько вопросов по этой проблеме, но я не нашел подходящего ответа на мою проблему. Первоначально я использовал следующий код после написания JSON в функции

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

Получал Server cannot append header after HTTP headers have been sent исключение.

Поэтому я изменил код

try {
    HttpContext.Current.Response.Write(Data);
    HttpContext.Current.Response.End();
} catch (System.Threading.ThreadAbortException exc) {
    try {
        //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();
    } catch (Exception ex) {
              //Log Exception
    }

}

Весь этот код работает (скажем так) writeData() и вызывается функцией под названием CallWriteData, Теперь исключение было успешно обработано WriteData() функция, но его бросание Thread was being aborted исключение в родительской функции CallWriteData,

Честно говоря, это не главная проблема в моем проекте, но было бы неплохо, если бы я исправил эту досадную проблему. Также это исключение в CallWriteData не каждый раз (иногда это успешно обрабатывается).

2 ответа

Решение

Наконец, это помогло мне справиться Thread was being aborted исключение,

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);
     }
   }

если вы используете следующий код вместо HttpContext.Current.Response.End(), ты получишь Server cannot append header after HTTP headers have been sent исключение.

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

Другое исправление, которое я нашел 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();
         }
   }

Теперь я с облегчением.

Вот как работает IIS. Он запускает новый поток для нового запроса. Поток делает свое дело, и когда он заканчивается, поток прерывается. Обычно это происходит в сантехнике.NET, и это там обрабатывается. Однако, если вы сделаете что-то вроде Server.Redirect(), оно также будет прервано - в вашем коде. Аналогично с выполнением запроса самостоятельно, как и вы. IIS говорит: "Отправлено возвращение, поэтому убейте его". Вот как это работает.

(Поток, вероятно, сохранен для повторного использования другим запросом, но только что завершенный код отменяется.)

Другие вопросы по тегам