问题
I'm currently having some problems with a method that throws an exception but I'm not sure why. The exception makes my application crash.
System.NullReferenceException: Object reference not set to an instance of an object.
at Myapp.AutoProcess.<ToRead>d__36.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<ThrowAsync>b__1(Object state)
at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
I run the method on a separate thread
Thread listenerThread = new Thread(() => ToRead());
listenerThread.Start();
The method that throws the exception looks like this:
private async void ToRead()
{
while (true)
{
if (this.toRead.Count != 0)
{
string protocol = this.toRead[0];
string[] temp = protocol.Split(',');
string message = temp[0];
string UserName = temp[1];
Process(message, UserName);
this.toRead.RemoveAt(0);
}
await Task.Delay(200);
}
}
It takes incoming messages from a List and filters out the Username and Message to send it to the Process method. I would appreciate if someone could help me out.
Note: The exception occurs about once a day running it on a Windows R2 2008 Server. Therefore I cant really debug it in Visual Studio
回答1:
You're seeing that exception crash your process because you're using an async void
method.
Instead of using a thread, use a task, as such:
private async Task ToReadAsync()
Task listenerTask = Task.Run(() => ToReadAsync());
And now you'll be able to nicely retrieve the exception in listenerTask.Exception
. But it probably won't give you much more detail.
What's probably happening is that your toRead
variable is set to null
at some point. The entire concept of the current code is wrong; polling like this is most definitely not the way to send data from one thread to another. Check out BlockingCollection
or something like that for a proper approach.
来源:https://stackoverflow.com/questions/21466488/async-method-throws-exception