The employee showed me very strange behavior, and I would like to know if anyone can explain to me why.
Basic constructor with 2 string parameters:
public MyClass(string str1, string str2) { this.s1 = str1; this.s2 = str2; this.s3 = Method(str2 + "._className", str1); }
Method:
public string Method(string key, string defaultValue) { List<string> list = _vars[key]; if (list == null) return defaultValue; string res = ""; foreach (string s in list) { if (res != "") res += ","; res += s; } return res; }
When this ctor is called on an aspx page with str2 as null , everything works fine, because if the string concatenation operand + is null , the empty string is replaced.
But when this ctor is called with str2 as null in the background thread, a NullReferenceException .
The problem was solved by testing str2 != null before using it, but I would really like to know why the same code sometimes throws an exception, sometimes not!
Here is the stack trace:
Exception: System.NullReferenceException Message: Object reference not set to an instance of an object. StackTrace: at MyClass..ctor(String str1, String str2) at AbandonedCartsNotificationJob.NotifyAbandonedCarts() in AbandonedCartsNotificationJobPartial.cs:line 39 at AbandonedCartsNotificationJob.work() in AbandonedCartsNotificationJob.cs:line 15 at MyRuntime.JobManager.run() at System.Threading.ThreadHelper.ThreadStart_Context(Object state) at System.Threading.ExecutionContext.runTryCode(Object userData) at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData) at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart()
Sylv21
source share