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;
}
NullReferenceException? pointer != reference (well, not strictly)BeginInvoke? is there any chance you're simply passing in a null state ? Also: for info, the handling ofIsBusyis dangerous in two different ways: ifEndInvokereports an exception, it'll never be marked as not busy, and you can't have more than one async task without corrupting that. Personally, I'd use an interlocked counter, but that might just be me.