I am facing NullPointerException in below code as it is happening very rarely and I tried to debug to replicate the issue but no luck. Can anybody help me what can cause NullPointerException here.
private static void MyTaskCompletedCallback(IAsyncResult res)
{
var worker = (AsyncErrorDelegate)((AsyncResult)res).AsyncDelegate;
var async = (AsyncOperation)res.AsyncState;
worker.EndInvoke(res);
lock (IsAsyncOpOccuring)
{
IsBusy = false;
}
var completedArgs = new AsyncCompletedEventArgs(null, false, null);
async.PostOperationCompleted(e => OnTaskCompleted((AsyncCompletedEventArgs)e), completedArgs);
}
Null Pointer exception is reported at
var async = (AsyncOperation)res.AsyncState;
Code from where I am invoking it
var context = HttpContext.Current;
AsyncErrorDelegate bkWorker = SendErrorMail;
AsyncCallback completedCallback = MyTaskCompletedCallback;
lock (IsAsyncOpOccuring)
{
if (IsBusy)
{
//Do we need to do something if repeated async getting call in case of error occuring at same time by different users.
}
AsyncOperation async = AsyncOperationManager.CreateOperation(null);
bkWorker.BeginInvoke(context,completedCallback, async);
IsBusy = true;
}
We can logically deduce that this is not actually the case.
If the line before worked, we know that
resis not null.AsyncStateisobject, so no custom operators are involved here, which means the cast is thus a type-check – which can either returnnull(without erroring), or can raise an invalid-cast exception.If you are seeing a
NullReferenceException, that leaves 2 options:resis null and it is the line above that is erroring (which: we shouldn’t actually expect – that will not happen)EndInvoke, the line after(the exact line often gets slightly confused when an exception is involved).
I suggest you add logging between each, to track what is happening. I also suggest you explicitly
tryaround theEndInvoke, since that can throw exceptions (it re-throws any exception from the async operation).In the more general case, a third option would have been:
AsyncOperationis astruct, andAsyncStateisnullHowever, in this case we can rule that out by deduction, because if
AsyncOperationwere astruct, the following would never box tonull(only an emptyAsyncOperation?would box tonull):