首页 > 代码库 > 【工作中遇到的问题】Dictionary 在进行Add操作使报超出了数组界限的问题

【工作中遇到的问题】Dictionary 在进行Add操作使报超出了数组界限的问题

问题代码的主要功能是用于记录页面的执行时间的:

 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.BaseController11 {12     public class TimeFilter : ActionFilterAttribute13     {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             try23             {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             try39             {40                 //计算出当前页面访问耗时41                 var costSeconds = (DateTime.Now - _start[currentThreadId]).TotalMilliseconds;42                 int value =http://www.mamicode.com/ Convert.ToInt32(costSeconds);43                 MetricClient.Instance.LogTiming(Name, value);44             }45             catch (Exception ex)46             {47                 LogWrapper.AddInfo("MobileHotel", "TimeFilter", "OnResultExecuted", ex);48             }49             finally50             {51                     _start.Remove(currentThreadId);52             }53         }54     }55 }

问题出现在第26行.

然后百度发现其他人也有发现此类问题,原因是dictionnary是多线程不安全的.需要加上锁

【工作中遇到的问题】Dictionary 在进行Add操作使报超出了数组界限的问题