问题代码的主要功能是用于记录页面的执行时间的:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Web.Mvc; 6 using TCWireless.Utility; 7 using System.Threading; 8 using TCBase.EagleEye.Metric; 9 10 namespace TCWireless.Controller.BaseController 11 { 12 public class TimeFilter : ActionFilterAttribute 13 { 14 public string Name { get; set; } 15 //创建字典来记录开始时间,key是访问的线程Id. 16 private readonly Dictionary<int, DateTime> _start = new Dictionary<int, DateTime>(); 17 public override void OnActionExecuting(ActionExecutingContext filterContext) 18 { 19 //过滤掉ChildAction, 因为ChildAction实际上不是一个单独的页面 20 if (filterContext.IsChildAction) return; 21 var currentThreadId = Thread.CurrentThread.ManagedThreadId; 22 try 23 { 24 if (!_start.ContainsKey(currentThreadId)) 25 { 26 _start.Add(currentThreadId, DateTime.Now); 27 } 28 } 29 catch (Exception ex) 30 { 31 LogWrapper.AddInfo("MobileHotel", "TimeFilter", "OnActionExecuting", ex); 32 } 33 } 34 public override void OnResultExecuted(ResultExecutedContext filterContext) 35 { 36 var currentThreadId = Thread.CurrentThread.ManagedThreadId; 37 if (!_start.ContainsKey(currentThreadId)) return; 38 try 39 { 40 //计算出当前页面访问耗时 41 var costSeconds = (DateTime.Now - _start[currentThreadId]).TotalMilliseconds; 42 int value = Convert.ToInt32(costSeconds); 43 MetricClient.Instance.LogTiming(Name, value); 44 } 45 catch (Exception ex) 46 { 47 LogWrapper.AddInfo("MobileHotel", "TimeFilter", "OnResultExecuted", ex); 48 } 49 finally 50 { 51 _start.Remove(currentThreadId); 52 } 53 } 54 } 55 }
问题出现在第26行.
然后百度发现其他人也有发现此类问题,原因是dictionnary是多线程不安全的.需要加上锁
时间: 2024-10-19 01:28:42