为什么在Task.Run中尝试try-catch-finally不能正常工作

时间:2019-05-06 10:43:02

标签: c asp.net-mvc

在生产环境中托管到IIS的ASPNetMVC服务有时会有一些奇怪的异常。

在异步中,最终会写入try-catch-final,并且try块中存在网络请求。通常情况下,当网络请求中发生异常时,捕获将捕获该异常。但是,生产服务器偶尔会有未被捕获的异常,并且捕获和最终执行的逻辑都不执行。

环境:

  • Windows服务2008 R2
  • IIS8
  • .Net Framework 4.5.2
public static string post(string url, string method, object postdata, bool iscache = false)
{
    var uuid = Guid.NewGuid().ToString().ToUpper().Split('-').ToList().Last() + " ";
    TraceLog.m_Trace.Trace(uuid + method + " url=" + url); // write log 1
    var rs = "";
    var key = "";
    try
    {
        var data = "";
        if (postdata is string)
            data = postdata as string;
        else
            data = Newtonsoft.Json.JsonConvert.SerializeObject(postdata);
        TraceLog.m_Trace.Trace(uuid + method + " postdata=" + data); // write log 2
        if (iscache)
        {
            // return cache ...
        }
        var req = (HttpWebRequest)WebRequest.Create(url);
        req.Headers.Add("Cache-Control", "no-cache");
        req.Headers.Add("MethodName", method);
        req.Method = "POST";
        req.ContentType = "application/json";
        var send = Encoding.UTF8.GetBytes(data);
        req.ContentLength = send.Length;
        req.Timeout = 60 * 1000;
        var nsm = req.GetRequestStream();
        nsm.Write(send, 0, send.Length);
        nsm.Close();
        var resp = (HttpWebResponse)req.GetResponse();
        var sm = resp.GetResponseStream();
        var sr = new StreamReader(sm, Encoding.GetEncoding("utf-8"));
        rs = sr.ReadToEnd();
        sr.Close();
        sr.Dispose();
        sm.Close();
    }
    catch (Exception ex)
    {
        TraceLog.m_Trace.Trace(uuid + method + " ex=" + ex.ToString()); // write log 3
        return new BaseResponse(ex.Message).ToString();
    }
    if (iscache && rs.Contains("IsSuccess\":true,"))
    {
        TraceLog.m_Trace.Trace(uuid + key + " wrrite cache..."); / write log 4
        CacheHelper.Max(key, rs);
    }
    TraceLog.m_Trace.Trace(uuid + method + " rs=" + rs); // write log 5
    return rs;
}

您遇到过这个问题吗?我用Google搜索了两天,没有找到类似的样本。希望得到您的帮助!在什么情况下会出现此问题以及如何解决?

0 个答案:

没有答案