【问题标题】:ThreadAbortException (WebClient using DownloadFile to grab file from server)ThreadAbortException(WebClient 使用 DownloadFile 从服务器抓取文件)
【发布时间】:2010-03-30 03:18:08
【问题描述】:

参考我的Earlier Question,关于从服务器下载文件并正确处理异常。我很肯定我已经解决了这个问题,然后以经典的编程方式,几天后回来沮丧地发现它坏了:-(


更新代码:

private static void GoGetIt(HttpContext context)
    {
        var directoryInfoOfWhereTheDirectoryFullOfFilesShouldBe = new FileInfo(......);
                var name = SomeBasicLogicToDecideName();

            //if (!directoryInfoOfWhereTheDirectoryFullOfFilesShouldBe.RefreshExists())
            //{
            //  throw new Exception(string.Format("Could not find {0}.", name));
            //}

            var tempDirectory = ""; //Omitted - creates temporary directory

            try
            {
                directoryInfoOfWhereTheDirectoryFullOfFilesShouldBe.CopyAll(tempDirectory);
                var response = context.Response;
                response.ContentType = "binary/octet-stream";
                response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}.zip", name));
                ZipHelper.ZipDirectoryToStream(tempDirectory, response.OutputStream);
                response.End();
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
                context.Response.StatusCode = 404;
            }
            finally
            {
                tempDirectory.DeleteWithPrejudice();
            }
        }

这工作正常,并返回 zip,否则如果文件不存在返回 404。然后在客户端我可以处理这个:

public bool Download()
{   
 try
                {
                    using (var client = new WebClient())
                    {
                        client.DownloadFile(name, tempFilePath);
                    }

                }
                catch (Exception)
                {
                    fileExists = false;
                }
return fileExists;
    }

但现在的问题是两件事。

1) 我得到 System.Threading.ThreadAbortException: 线程在服务器端 try-catch 块中被中止。通常这只是一个未找到文件的异常。我不知道抛出什么或为什么抛出新异常?

2) 现在服务器端抛出了一个不同的异常,而不是找不到文件,看来我不能为应用程序使用这个设置,因为回到客户端,任何异常都被假定为找不到文件。

任何帮助,尤其是有关为什么抛出此 ThreadAbortException 的信息!?!?非常感激。干杯

【问题讨论】:

  • 在不相关的说明中,捕获特定异常(在这两种情况下)而不是所有异常可能会更好。

标签: c# .net asp.net exception-handling httpresponse


【解决方案1】:

问题在于Response.End() 抛出了一个 ThreadAbortException:这就是它结束请求的方式。完全摆脱那个电话,你不需要它。

【讨论】:

  • 这很简单!谢谢。虽然我发誓我几乎可以肯定我在那里与那条线一起工作。奇怪。
  • 很奇怪。我现在已将服务器端捕获更改为 catch (DirectoryNotFoundException dnfEx) 并离开 response.End() 现在似乎不再抛出异常?
  • 它仍然会抛出,但你不再捕捉它了。运行时知道 ThreadAbortException 只是意味着结束请求,因此不会报告它。
  • 啊,这一定是我之前所做的,当时我确定它正在使用该行并忘记我更改了它。但就像你提到的那样,我应该完全摆脱它吗?
  • 是的,不需要。您可以在某处的某个嵌套调用中使用它作为取消请求或其他内容的快速方法,但在正常程序流程中不需要它。
猜你喜欢
  • 1970-01-01
  • 2012-07-03
  • 1970-01-01
  • 1970-01-01
  • 2011-02-06
  • 1970-01-01
  • 2010-09-20
  • 2015-01-04
  • 1970-01-01
相关资源
最近更新 更多