在工厂startnew中向字典中添加项目时,代码将引发NullReferenceException

时间:2019-07-11 03:18:28

标签: c# asp.net multithreading dictionary

我有C#代码;当运行到一行时,它抛出一个Ln = Wb.VBProject.VBComponents("Module1").CodeModule.ProcStartLine("ErrorProducingMacro", 0) Wb.VBProject.VBComponents("Module1").CodeModule.InsertLines Ln + 2, "On Error Resume Next" Run Wb.Name & "!ErrorProducingMacro"

这是引起异常的代码行

System.NullReferenceException

这是代码中的堆栈跟踪

if (expDic != null && expression != null)
{
    expDic.Add(i, expression.ToString())
}

我发现 at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add) at System.Collections.Generic.Dictionary`2.Add(TKey key, TValue value) at Sustainability.BusinessObject.CalculationManager.<>c__DisplayClass18_0.<HandleFormulaInner>b__0(Object args) in D:\HK\Desktop\VSTS_2\Sustainability.BusinessObject\Classes\CalculationManager.cs:line 1410 at System.Threading.Tasks.Task.InnerInvoke() at System.Threading.Tasks.Task.Execute() expDic都不为空,但是它引发了空引用异常。

这是我的代码:

expression

我怀疑这是由 int count = table.Rows.Count; Dictionary<int, string> expDic = new Dictionary<int, string>(); List<Task> taskList = new List<Task>(); for (int f = 0; f < count; f++) { DataRow tempformula = table.Rows[f]; string formulaSymbol = Convert.ToString(tempformula[Common.Systems.Sustainability.Constants.IndicatorFormula.Symbol]); var t = Task.Factory.StartNew(new Action<object>((args) => { int i = (int)args; _sem.Wait(); StringBuilder expression = new StringBuilder(1024); using (DataTable dt = new DataTable()) { // symbol in the last line of formula if (exp.EndsWith("+") || exp.EndsWith("-") || exp.EndsWith("*") || exp.EndsWith("/")) { exp = exp.Substring(0, exp.Length - 1); } object result = dt.Compute(exp, ""); expression.Append(result); } } { if (!string.IsNullOrWhiteSpace(symbol) && expression.Length > 0) { if (i + 1 >= count && symbol != ")") { } else if (expression.ToString() != symbol) { expression.Append(symbol); } } else if (expression.Length == 0 && symbol == "(") { expression.Append(symbol); } if (symbol == "days") { // calculating average values by days. if (fromDate != null && toDate != null) { int days = toDate.Value.Subtract(fromDate.Value).Days + 1; expression.Append(days); } else { expression.Append(1); } } } //Here is the code will have problem if (expDic != null && expression != null) { expDic.Add(i, expression.ToString()); } _sem.Release(); }), f); taskList.Add(t); } 多线程模式引起的, 那么我的代码有什么问题,我该如何解决?

0 个答案:

没有答案